Tuesday 18 February 2014

Why Strings are immutable in Java ?

As in Java, String literals are placed in String pool and whenever the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created and existing string has additional reference.

For example :--

String string1 = "abcd"; //This statement will keep a string literal in String pool on heap.

String string2 ="abcd"; // When this statement is executed, JVM again encountered a string literal, so JVM will check the pool to see if an an identical string literal already exist. In this case match is found. So instead of returning new reference, string2 variable holds the same reference as of string1 variable but string literal "abcd" has multiple references through string1, and string2.





As program grows, several references may refer to same string literal object in pool without knowledge of each other. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references which might lead to undesired results.

Hence String was made immutable. String pool concept would not have been feasible if String were mutable. 
 


No comments:

Post a Comment