Ad

Wednesday 19 August 2009

Why String is called as immutable object?

As everyone knows String is called as immutable object.what does immutable object means? An immutable object is the one, whose state can't be changed or modified after its initial construction.

Lets take the below code

String s1=new String ("immutable"); // A new String object will be created("immutable") and s1 refer to it.
System.out.println("String-"+s1);
s1=s1.toUpperCase(); //A new string object will be created("IMMUTABLE") and s1 refer to it.
System.out.println("String-"+s1);

Output will be
String-immutable
String-IMMUTABLE

So when we try to modify the string object("immutable") by calling the toUppercase method on reference s1,a new string object is created instead of applying the changes to the existing object. Thus s1 will refer to the new object("IMMUTABLE") created and the old object("immutable") will lose the reference.
Hence there will be two objects created in the memory:

  1. A string object "immutable" which has no reference(become eligible for garbage collection) and
  2. A new String object "IMMUTABLE" which is  referred by S1.

Hence if we try to alter/modify a string object,it creates a new string object instead of altering the existing object and the existing object will become eligible for garbage collection.

StringBuilder and StringBuffer classes are not immutable object.Hence if we try to make changes to these object,it will apply the changes to the same object instead of creating a new one.

Note:Wrapper classes(like Integer,Float etc) too have this immutable behaviour

No comments:

Post a Comment