Saturday, February 9, 2013

why String is immutable

Immutable means that the current object is unchangeable & operations on it will return another new object which you have to catch to see the changes.  String class is such class where methods like toUpperCase() etc will return String object which you have to save in a new variable....
however if their is a long string of operations & you dont want to make many variables
you can always use StringBuffer or StringBuilder class where all operations are performed on original object without the need to create multiple new objects.......


String s1= "samba";
s1.toUpperCase();
then s1 will not automatically point to a new String variable at another memory location.
 s1 would still be pointing to the original String object, and the new String object that comes out of toUpperCase() will be ignored and thrown away.  If you wanted s1 to point to the new String, you must assign it explicitly:

Assign the result of the method to name
s1= s1.toUpperCase();

example:


package com.samba.org.sample;

public class StringImmutableTest {

public StringImmutableTest()
{
System.out.println("StringImmutableTest.StringImmutableTest()");
}

public static void main(String[] args)
{

String s1="samba";

System.out.println("Before String Operation hash code:"+s1.hashCode());
s1.toUpperCase();
System.out.println("After String Operation but nt assigned to any variable hashcode:"+s1.hashCode());
s1=s1.toUpperCase();
System.out.println("After String Operation and assigned to variable hashcode:"+s1.hashCode());

/*OUTPUT
*
* Before String Operation hash code:79649854
* After String Operation but nt assigned to any variable hashcode:79649854
* After String Operation and assigned to variable hashcode:78664766
                 *
*/
}

}





No comments:

Post a Comment