Friday 20 July 2012

string


String is immutable:
String s1 = gopal;
String s2= Krishna;
s1 = s1+s2;
System.out.println(s1);
Output:
gopalkrishna
the output of the program “gopalakrishna” . it seems that the string s1 content is modified. Earlier s1 got “gopal” and s2 had “Krishna”. After s1+s2, they are joined and total string become “gopalakrishna”. This string is assigned to s1 again. If s1 is mutable, it gets new string “gopalakrishna”. This is what we can see in the output. So s1 appear to be mutable. But we learned that strings are immutable.
s1 is definitely immutable. But why the output of the program like that? In the program, jvm creates two objects, s1 and s2 seperately, as shown in the below figure. When s1+s2 is done, jvm creates new object and stores the new object and stores the string “gopalakrishna” in that object. But it doesn’t modify the contents of the string s1. After creating new object, the reference “s1” is adjusted to refer to that new object. The point we should observe here is that the contents of the string s1 are not modified. This is the reason string objects are immutable. The old object that contains “gopal” has lost its reference. So it is called “unreferenced object” and garbage collector will remove it from memory.

No comments:

Post a Comment