Monday, 18 November 2013

JAVA: Why Strings are immutable in JAVA

First lets have the definition of the Immutability
Immutability of an object is that the state of an object(hashcode content) cannot be changed once its created.

Let me show you one example which is mutable.
Consider the class StringBuilder.

StringBuilder sb = new StringBuilder("asla");
        System.out.println(sb.hashCode());                // out put : 817639612
        System.out.println(sb);                                   //asla
        sb.append("m");
        System.out.println(sb.hashCode());                 // out put : 817639612
        System.out.println(sb);                                   // aslama
        sb.append("an");
        System.out.println(sb.hashCode());                  // out put : 817639612
        System.out.println(sb);                                     //aslaman


In the above example you can see the same hashcode is being overriden with different values thats why the object sb is mutable in the above example.


Now lets consider strings.   
        String x ="IBM";
        System.out.println(x.hashCode());       //72276
         x = x+"india";
        System.out.println(x.hashCode());       //-873372829

now the same object x has different hashcode when its concatenated. what happened to the value which is there in 72276?
Its still there . So string object state once created cannot be changed , hence strings are immutable.

 Why
Strings have concept called string pooling.
String x = "IBM"
String y = "IBM"

In the above example only one object is created x and string y has the same reference as that of x .
This is the benefit of having String pooling. So Strings with same value will have only one object.

Now if we change the value of x say x = x+ "INDIA";
JVM cannot allocate the value of the x as IBMINDIA in the same reference which its pointing because y's value is IBM , you cannot make it IBMINDIA. Hence the reference which is having the value IBM will be there and cannot be changed as strings are immutable . JVM Will create new reference for x with the value IBMINDIA and x will be pointing to that.


Now its clear that why strings are immutable.

There are other reasons as well I have just discussed the main reason for Strings immutability.


No comments:

Post a Comment