Pages

Tuesday 19 May 2015

Immutable Nature of String

     Immutable means cannot be changed or altered. String instance once created are immutable. But still you can perform all type of operations like appending, reversing the string etc. Each time you perform any of these operations, a new string instance is formed and the original string on which operation is performed is unchanged.

      The below example program justifies the immutable nature of string:


public class MyStringImmutable
{
  public static void main(String[] args)
  {
       
        String str1="Coding"; // string literal.
       
        str1=str1.concat(" Unlimited");
       
        System.out.println(str1);
       
       

  }
}

Output:  

Coding Unlimited

      Now lets us see what happens when the above program is executed:

            String str1="Coding";

   After the execution of above line a new string instance “Coding” is formed and placed in string constant pool and variable str1 has the reference to the instance.

          str1=str1.concat("Unlimited");

      
      After the execution of above line the string instance “Coding” is concatenated with “Unlimited” to form a new string instance “Coding Unlimited” and it is also placed in string constant pool. The variable str1 now refers to “Coding Unlimited”.

What is the advantage of immutable nature of String?


   Suppose consider there are 3 reference variables, all referring to one object “Coding”. If anyone of the 3 reference variables tries to change the value of string object and if suppose string was mutable object then change will affect all three reference variable, this may not be desired in all circumstances. So to avoid such situation string objects are immutable in java.