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

[1067 byte] By [ritu_jainna] at [2007-11-27 10:39:46]
# 1

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 > top of Java-index,Java Essentials,New To Java...
# 2

why should it be?

jwentinga at 2007-7-28 19:03:01 > top of Java-index,Java Essentials,New To Java...
# 3

By the way, calling intern() on a String literal is pointless, since literals are already interned.

jverda at 2007-7-28 19:03:01 > top of Java-index,Java Essentials,New To Java...
# 4

> ...

> 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 -> +-+

*/

prometheuzza at 2007-7-28 19:03:01 > top of Java-index,Java Essentials,New To Java...
# 5

thanks for the answer. and thanks for the wonderful thought of using the graphical representation.. it was much easier to understand from that.

thanks.

ritu_jainna at 2007-7-28 19:03:01 > top of Java-index,Java Essentials,New To Java...
# 6

> 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.

prometheuzza at 2007-7-28 19:03:01 > top of Java-index,Java Essentials,New To Java...