Hi,
During a recent team discussion, we thought we read somewhere that
this was added to 1.5 as default behaviour, but we were not sure. By
automatically interning I mean that if you have String a = new
String("ABC") then
String str = new String("ABC")
is equivalent to
String str = a.intern();
Thus far, we have found nothing to say that this was added.
It was not.
You have to read between the lines a bit, but the JLS forbids this
optimization if its effects would be detectable. Follow along, if you
will:
1. 15.21.3 states that "At run time, the result of == is true if the
operand values are both null or both refer to the same object or
array; otherwise, the result is false."
2. 4.3.1 states that "An object is a class instance or an array." and
that "A class instance is explicitly created by a class instance
creation expression." The reference for that second statement covers
expressions of the form 'new Type (Arguments)', which implicitly
includes 'new String ("Some literal")'.
Those two statements combine to imply that
String a = new String ("foo");
String b = new String ("foo");
boolean same = (a == b);
will always result in 'same' containing false, eg., that the two
objects are not the same instance.
3. 3.10.5 states, "String literals-or, more generally, strings that
are the values of constant expressions (§15.28)-are "interned" so as
to share unique instances, using the method String.intern," which
doesn't cover new expressions, and the documentation for String.intern
follows this with
"for any two strings s and t, s.intern() == t.intern() is true if
and only
if s.equals(t) is true."
which implies that were strings automatically interned such that 'new
String ("foo")' evaluated to an interned instance of "foo", then
String a = new String ("foo");
String b = new String ("foo");
boolean same = (a.intern () == b.intern ());
would result in 'same' being set to true, since a.equals(b) and the
strings would have been interned.