String

Posted: June 20, 2012 in Java

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s