Thursday, March 12, 2009

Strings are immutable, How are we able to perform concatination on

Question :Strings are immutable, How are we able to perform concatination on
String object? (CoreJava)

Answer :Yes. Strings are immutable. Thats why while concatenating, it always
returns a new string object.
If we take this example :
String s1 = "psn";
s1 = s1.concat("prasad"); // Here you are reassigning the new object to
the older reference s1
System.out.println(s1);
String s1 = "psn";
String s2 = s1.concat("prasad");
System.out.println(s1); // will remain same . no change. it prints "psn"
only
System.out.println(s2); // as you have assigned the newly created object
to s2

No comments: