Monday, September 26, 2011

String Object is immutable (example)


//Bellow program shows that String Object is immutable
package StringBufferedPackage;

public class StringObjectIsImmutable
{
public static void main(String[] arun)
{
String name = "Arun";
System.out.println("Initially name is "+ name);
//the above print statement print "Initially name is Arun"

name.concat(" Kumar");
System.out.println("After concat middle-name name print like => "+name);
//this println print as "After concat middle-name name print like => Arun" i.e concatenation didn't done here.

name = name.concat(" Kumar");
System.out.println("After creating a new string object the name become : "+name);
//it prove that string objects are immutable.
}
}


Output=>
Initially name is Arun
After concat middle-name name print like => Arun
After creating a new string object the name become : Arun Kumar

No comments:

Post a Comment