Immutable Strings in Java: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-07-04 04:49:53   8274  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string?

String s = "Man";
s = "Woman";

The answer is no. The first statement creates a String object with the content "Man" and assigns its reference to s . The second statement creates a new String object with the content "Woman" and assigns its reference to s . The first String object still exists after the assignment, but it can no longer be accessed, because variable s now points to the new object, as shown in Figure below.

Immutable String in Java

Because strings are immutable and are ubiquitous in programming, the JVM uses a unique instance for string literals with the same character sequence in order to improve effi- ciency and save memory. Such an instance is called an interned string. For example, the fol- lowing statements:

immutable string in java

In the preceding statements, s1 and s3 refer to the same interned string— " Welcome to atnyla " —so s1 == s3 is true . However, s1 == s2 is false , because s1 and s2 are two different string objects, even though they have the same contents.


Let's try to understand the immutability concept by the example given below:

class Testimmutablestring{  
 public static void main(String args[]){  
   String s="Man";  
   s.concat("Woman");//concat() method appends the string at the end  
   System.out.println(s);//will print Sachin because strings are immutable objects  
 }  
}  

Output

Man
press any key to continue... 

Now it can be understood by the diagram given below. Here Man is not changed but a new object is created with ManWoman. That is why string is known as immutable.

immutable string

As you can see in the above figure that two objects are created buts reference variable still refers to "Man" not to "Man Woman".

But if we explicitly assign it to the reference variable, it will refer to "Man Woman" object. For example:

class Testimmutablestring1{  
 public static void main(String args[]){  
   String s="Man";  
   s=s.concat(" Woman");  
   System.out.println(s);  
 }  
}    

Output

Man Woman
press any key to continue... 

In such case, s points to the "Man Woman". Please notice that still Man object is not modified.