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, synchronisation and data structures.
The following code initializes a string s.
String s1= “abc”;
This can be denoted by following diagram:
But when we assign the same String to another String then rather than allocating the memory, it points to the same object
String s2 = s;
Memory heap representation |
s2 stores the same reference value since it is the same string object.
But when we concatenate a string “ef” to s,
But when we concatenate a string “ef” to s,
s = s.concat(“ef”);
Conclusion
Once a string is created in memory(heap), it can not be changed. All methods of String do not change the string itself, but rather return a new String. If we need a string that can be modified, we will need StringBuffer or StringBuilder.