Immutability of Strings

Immutability of Strings

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 –

package com.code2succeed.string;

public class StringImmutableTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = "Code2";
		String str2 = "Succeed";
		System.out.println("String 1: "+str1);
		System.out.println("String 2: "+str2);
		//join str1 and str2 and store in str1
		str1 = str1 + str2;
		System.out.println("String after join: "+str1);




String 1: Code2
String 2: Succeed
String after join: Code2Succeed


Please observer the statement –

str1 = str1 + str2;

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 *