Reputation: 1191
While trying the understand the reasons behind why strings are immutable, I wrote a simple program as follows:
/* Program to test string immutability */
public class StringImmutability
{
public static void main(String args[])
{
String s = "hello";
s.concat(" world"); // returns a new string object. So, the reference must point to this object for further processing like this: s = s.concat(" world");
System.out.println(s);
s = s.concat(" world");
System.out.println(s);
String s1 = s, s2 = s, s3 = s;
System.out.println(s1+" "+s2+" "+s3);
s = s.concat(" test");
//The references are modified
System.out.println(s1+" "+s2+" "+s3);
}
}
The output though isn't as expected:
hello
hello world
hello world hello world hello world
hello world hello world hello world
After the references are modified, the output must be hello world test
repeated thrice but there isn't any change in output.
Upvotes: 0
Views: 242
Reputation: 95488
It is working exactly as expected. Let's look at it step by step:
String s = "hello";
s.concat(" world");
This is effectively a NOP because you are not assigning the result of concat
to anything. That new String
instance is lost to the ether and garbage collected since there is nothing referring to it. Hence, your s
remains unchanged.
s = s.concat(" world");
Here s.concat(" world")
returns a new String
instance, and you have reassigned s
to that. So s
now points to this new string and you have lost the reference to the older one (the one that just had hello
in it).
String s1 = s, s2 = s, s3 = s;
Here you have created three variables that all point to the same string instance that s
points to.
s = s.concat(" test");
This is a repeat of what you did earlier. concat
creates a new string instance and you reassign s
to that. But keep in mind that s1
, s2
, and s3
are still pointing to what s
used to point to and so they will not reflect the changes.
You've only stopped s
from pointing to the old string and made it point to the new one. But your other variables are still pointing to that old string.
Upvotes: 15
Reputation: 279880
s
is reassigned to a new string that has the " test"
String
appended to the end of the target String
value (s
pre-assignment).
s = s.concat(" test");
This does not affect the String
value stored in s1
, s2
, or s3
, since concat
returns a new String
object.
Upvotes: 6
Reputation: 285415
Your code proves String immutability. You can change the String that a variable refers to, but you can't change the String object itself (other than through shifty reflection tricks that I won't discuss here). The error above is in your expected output and nothing else. For example,
s = s.concat(" test");
creates a new String object and assigns it to the s
variable. It does not and cannot change the original object that s
referred to.
Upvotes: 7