String intern
publicclass Test
{
Test()
{
String s1 ="original".intern();
String s2 ="original".intern();
System.out.println("1.." + s1 +"..2.." + s2);
s1 ="changed".intern();
System.out.println("1.." + s1 +"..2.." + s2);
}
publicstaticvoid main(String[] args)
{
new Test();
}
}
If intern returns the same object from the pool of strings, why is s2 not changed to "changed"?
Output is : 1..original..2..original
1..changed..2..original
For reference variables, when you do x = something, you're just pointing a reference at an object. Changing to x = somethingElse later doesn't change the object, and it doesn't change any other references that are pointing to that original object. It just makes x point to some other object.
jverda at 2007-7-28 19:03:01 >

> ...
> If intern returns the same object from the pool of
> strings,
Which only means s1 and s2 point to the same String (in other words: s1 == s2)
> why is s2 not changed to "changed"?
Because you never assigned a new String to s2.
This is what happens:
String s1 = "original".intern();
String s2 = "original".intern();
/*
s1 -> +-+
|"original"|
s2 -> +-+
*/
s1 = "changed".intern();
/*
+-+
|"changed "|
+-> +-+
|
s1 --++-+
|"original"|
s2 -> +-+
*/
> thanks for the answer. and thanks for the wonderful
> thought of using the graphical representation.. it
> was much easier to understand from that.
>
> thanks.
You're welcome.