Immutability of Strings

Posted on

In java, we can divide objects broadly as mutable and immutable. Since we know that mutable objects are those whose content can be modifies whereas Immutable objects once created cannot be modified. And String class objects are immutable.

Let take an example to understand whether String objects are immutable or mutable –



Please observer the statement –

Output of the program is “Code2Succeed”. It seems that the string str1 content is modified. Earlier str1 got “Code2” and str2 had “Succeed” and after str1 + str2 it becomes “Code2Succeed”. Since str1 + str2 is assigned to str1 again, suppose if str1 is mutable then it gets the new string “Code2Succeed” and this is what we can see in the output. So str1 appears to mutable. But we learned that String is immutable.

As per the concept str1 is definitely immutable. But then why the output of the program is like that ?
In the program, JVM creates two objects, str1 and str2 separately. When str1 + str2 is done, JVM creates a new object and store the string “Code2Succeed” in that object. But it doesn’t modify the content of the string str1. After creating the new object, the reference str1 is referred towards new object. The point we should observer that the content of the String str1 are not modified. The old object that contains “Code2” has lost his reference and new object “Code2Succeed” is referred by str1. So “Code2” is unreferenced object and garbage collector will remove it from memory.


To maintain the immutable nature, none of the String class method should be able to modify the contents of the object. So JavaSoft people did not provide the methods in String class which modify the contents of the objects. Whenever we try to modify the content, JVM will create a new object with modified data. Also there should not be any scope to override those String class methods. This is the reason, String class is made ‘final’ class. The method of final class cannot be overridden.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.