Why String is immutable in Java?


Reading time: 10 minutes | Coding time: 5 minutes

An immutable object is an object whose internal state remains constant after it has been entirely created.This means that the public API of an immutable object guarantees us that its behaviour will remain same and will not change during its whole lifetime.

In Java, Strings are immutable which means that the existing String objects can't be changed i.e we can't modify the existing String objects or we can't change the internal state of the String objects.

Example

code

class Testing{  
 public static void main(String args[]){  
   String str="Swati";  
   str.concat(" Priya"); //concat() method appends the string at the end  
   System.out.println(str);//will print Swati because strings are immutable objects  
 }  
}  

Output

Swati

The above code can be understood with the help of the diagram given below:

string_immutability_example

Here "Swati" is not changed but a new object is created with "Swati Priya". That is why string is known as immutable.Also, you can see in the figure that two objects are created but str reference variable still refers to "Swati" not to "Swati Priya".

Code

class Testing{  
 public static void main(String args[]){  
   String str="Swati";  
   str=str.concat(" Priya");  
   System.out.println(str);  
 }  
}

But if we will explicitely assign it to the reference variable, it will refer to "Swati Priya" object but still the "Swati" Object will not be modified.

The advantages of having Strings as immutable in Java includes:

  • Caching
  • Hashcode Caching
  • Better Performance
  • Synchronization
  • Security

We will explore each of the benefits in depth now.

Caching

The String literals are cached and are stored in String constant pool.String constant pool is the special memory region where Strings are stored by the Java Virtual Machine (JVM).This process helps in the memory optimization as Java Virtual Machine (JVM) allows only to keep one copy of the each string literal in the memory space i.e if different String variables refers to the same String literal then only one copy of the string literal will be stored in the String pool and all other string variables will be pointing to the same String object in the pool.Objects inside String constant pool can't be changed because if it is changed then the values of other variables pointing to the same object will also change.

Code

String str1 = "I love Java";
String str2 = "I love Java";
          
assertThat(str1 == str2).isTrue();

String_pool

Hashcode Caching

String objects are widely used for the hash implementations like HashMap,Hashset,HashTable,etc.It is mostly used as a key in the hash implementations because Java Virtual Machine (JVM) calculates the hashcode using all the characters present in the string and then the hashcode value is cached into the string object as hash and next time, if the same string will appear then its hashcode will not be calculated but the same hash value will be used for the same string because of the string's immutability feature.This saves a lot of time as calculating hashcode is very time consuming.The method used for bucketing when operating upon these hash implementations is hashCode() method.

Code

class Hash{
    public static void main(String[] args){
        String str1 = "I love Java";
        String str2 = "I love Java";

        if(str1.equals(str2)){
            System.out.println("Equal variables:");
            System.out.println(str1.hashCode() + "\n" + str2.hashCode());
        }
    }
}

Output

Equal variables:
-1505412327
-1505412327

Better Performance

As seen earlier in Caching,We can save a lot of Heap Memory Space as duplicate string objects are not allowed because of the string's immutability feature.
Also,the hash implementations using strings saves a lot of time as we don't need to calculate hashcode for the string literal having same value.

Thus, both memory optimization and faster access is obtained which automatically ensures the better performance of the whole application in general.

Synchronization

String's immutability feature makes it safe for multithreading as it won't change even if it is accessed from multiple threads.

Thus, in general, the immutable objects can be shared across multiple threads running simultaneously.Even if the thread changes the value of the string then the new string object will be created in the string pool and the existing string will not be modified.Thus, the strings are thread safe because of its immutability feature.

Security

The String is widely used in Java Application to store important informations like username,password,etc.

For example:

username and password is passed as a string in the database to get the database connection and also in socket programming port details and host are passed as a string.Had the string been mutable it would have been possible for the hacker to access our personal data and also change the referenced value to cause security threats to our application.

It is also used by Java Virtual Machine (JVM) class loaders while loading classes.So, immutability provides the guarantee that correct class is getting loaded by the Classloader.

For example:

Had the strings been mutable and for an instance if we were trying to load java.util.Connection class but due to some breaks in between our string got changed from java.util.Connection to hacked.Connection class then our database will be in danger.

Code

public class MyApi {
    final String store_url;
    public MyApi(String passed_url)
    {
      // Verify that passed_url points to an approved server
        if (!checkApprovedUrl(passed_url)) throw new IllegalArgumentException();
        store_url = passed_url;
    }
}

If the strings were mutable then in the above code, the attacker would have passed a good url and then changed it to a attack url which can cause serious security issues.

Thus,to ensure the security of the whole application it is crucial to secure the Strings.

Conclusion

Thus, with this article at OpenGenus, these are the reasons which answers the question "why String is immutable in Java".If you think there are some reasons then comment down in the discussion section given below.