Why String is immutable in Java?

String is immutable in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified. There are many advantages of immutable classes. This article summarizes why String is designed to be immutable. This post illustrate the immutability concept in the perspective of memory, synchronization and data structures.

Read more

Monitors – The Basic Idea of Java Synchronization

If you took operating system course in college, you might remember that monitor is an important concept of synchronization in operating systems. It is also used in Java synchronization. This post uses an analogy to explain the basic idea of “monitor”. 1. What is a Monitor? A monitor can be considered as a building which … Read more

Java equals() and hashCode() Contract

The Java super class java.lang.Object defines two important methods: public boolean equals(Object obj) public int hashCode()public boolean equals(Object obj) public int hashCode() In this post, I will first show an example of a common mistake, and then explain how the equals() and hashCode() contract works. 1. A common mistake The common mistake is shown in … Read more

Diagram of Exception Hierarchy

In Java, exception can be checked or unchecked. They both fit into a class hierarchy. The following diagram shows Java Exception classes hierarchy. Red colored are checked exceptions. Any checked exceptions that may be thrown in a method must either be caught or declared in the method’s throws clause. Checked exceptions must be caught at … Read more

The Interface and Class Hierarchy Diagram of Java Collections

1. Collection vs Collections First of all, “Collection” and “Collections” are two different concepts. As you will see from the hierarchy diagram below, “Collection” is a root interface in the Collection hierarchy but “Collections” is a class which provide static methods to manipulate on some Collection types. 2. Class hierarchy of Collection The following diagram … Read more

Diagram to show Java String’s Immutability

Here are a set of diagrams to illustrate Java String’s immutability. 1. Declare a string The following code initializes a string s. String s = "abcd";String s = "abcd"; The variable s stores the reference of a string object as shown below. The arrow can be interpreted as “store reference of”. 2. Assign one string … Read more