All.I have a java code snippet like this:
String a = new StringBuilder("app").append("le").toString();
System.out.println(a.intern() == a);
String b = new StringBuilder("orange").toString();
System.out.println(b.intern() == b);
and this java code will output true,false. I wonder why. Thanks All.
In both cases, StringBuilder.toString()
creates a new string.
In the first case, String.intern()
finds that there's no string "apple" in the intern pool, so adds the provided one to the pool and returns the same reference - which is why it prints true
.
In the second case, String.intern()
finds that there's already a string "orange" in the intern pool, so returns a reference to that - which is a different reference to b
, hence it prints false
.
Note that if you had a line before the start of this code of:
System.out.println("apple");
then you'd see false
from the first comparison too, for the same reason.
See more on this question at Stackoverflow