Strings in Java II: Immutability

Immutability is the most touted feature of Java Strings. Indeed it is quite unusual for a programming language to impose immutability on a data type. As we will see in this lesson, immutability of Java Strings is desirable feature. This is not the case with other programming languages. Java, because it allows you to create new object using literal notation, must make its Strings immutable.

So, What is Immutability?

Immutability of Java Strings means that value of a Java String cannot be changed. So, a Java String is a constant.

Recall from the previous lesson that constant is actually a variable whose value cannot be modified. Since the value of a Java String cannot be modified, Java Strings are constants.

Remember that immutability does not mean that a String variable cannot start pointing to a new value. It means that the value of a string cannot change.

If you do some mutating operation on a String, your string variable starts pointing to a new value.

An Example of Immutability of Java String

The following code demonstrates that we can never change the value of a String. The string variable can point to a new variable and thus the value may appear changed, but in the memory the old value remains unmodified.

Look at the code below

Note that bestSite merely shifts the address it is pointing to. You create a new string when you say

The above code does not modify the string “CodingRaptor” but creates a new one “CodingRaptor.com” and assigns it to the variable bestSite.

The diagram below further captures these concepts –

Why are Java Strings Immutable?

In the example above, it may appear that there is memory wastage. After all we abandoned the string “CodingRaptor” and hopped on to “CodingRaptor.com“. So, an operation that should have modified an object created a new one. Wastage, isn’t it?

Actually, it will not. Java has an excellent support for garbage collection. Any unused objects (even if they are in PermGen space) will be claimed back. Moreover, there is always a chance that a string which is used once will be used again. In such a case Java will return reference from the string pool rather than creating a new object.

Apart from this main reason there are other reasons as well for making Java Strings immutable.

  1. Java’s string literals reside in constant po0l. (Discussed above and elaborated in previous lesson). In order to ensure that the value of String does not change unexpectedly.
  2. Java Strings are used quite often required to participate in multithreaded programs. Immutability in a multithreaded environment means that we don’t need to apply any synchronization constructs on the strings. We can freely share the strings between threads. This results in a lot of performance gains.
  3. Since strings are immutable their hash code cannot change. This gives an opportunity to cache the hash code. Through caching we would need to calculate the hash value once and just reuse it subsequently.

Myths About Advantages of String Immutability

There are a lot of bogus advantages of immutability cited. Most often a job seeker who does not know about the advantages of immutability comes up with a made up confused answer. This made up answer and hearsay is further added to the plethora of existing bogus advantages.

For example, security is NOT achieved by making Strings immutable. If you pass some method a String it can always chose to ignore the passed value and assign a different value to the variable holding the parameter. Note that it is the value of the string which is immutable. The variable holding the address  of the immutable String can always point to a new String. (In fact that’s how mutating operations such as concatenation work.)

Similarly, security during class loading is NOT attained by making String immutable. An intruder smart enough to change your bytecode and fool the Java verifier will surely know that he can make the String variable point to a new value.

Betterment of other objects, or facilitation use of objects is another bogus advantage. Immutability of String was not implemented so that some other data structure may function correctly. Moreover, String pre-dates HashMap and HashSet like data structures by a full decade or so.  Designers of Java String, though genius, are not Nostradamus to foresee hash based data structures coming a decade later.

Leave a comment

Your email address will not be published. Required fields are marked *