Why String is immutable in Java ?

The term Mutable means "can change" and Immutable means "cannot change". An Immutable Object means that the state of the Object cannot change after its creation. Here the String is immutable means that you cannot change the object itself, but you can change the reference to the object. Changing an object means to use its methods to change one of its fields or the fields are public (and not final ), so that you can be updated from outside without accessing them via methods. Once string object is created its data or state can't be changed but a new string object is created. An important point to note here is that, while the String object is immutable, its reference variable is not.
String str1="Hello"; System.out.println("str1 is "+a); String str2 = str1; str1 ="World!!"; System.out.println("str1 after modify "+a); System.out.println("str2 is "+b);
str1 is Hello str1 after modify World!! str2 is Hello
Here we see the difference between mutating an object, and changing a reference. str2 still points to the same object as we initially set str1 to point to. Setting str1 to "World!!" only changes the reference, while the String object it originally referred to remains unchanged.


Immutability of strings has positive significance in multithreaded applications because it provides automatic thread safety. Instances of immutable types are inherently thread-safe , because no thread can modify it. Also, String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were S tring not immutable , a connection or file would be changed and lead to serious security threat.


The main drawback of immutable types is that they require more resources than other object types. Because each time it modified, it creates a new one.
String str=null; for(int i=0;i < =100;i++){ str+="Add this"; }


The above code segment creates 1000 new string variables. In these type of situations you should use the Java StringBuilder class, which allows you to modify the text without making new String class instances. Java StringBuilder is a Mutable type, that means when you alter it , it still holding same data Example
public class TestClass{ public static void main(String[] args) { StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < 1000; i++) { sBuilder.append("Add This"); } String str = sBuilder.toString(); } }