■ Interning is used by String
only. It is the default as long as new
isn’t used.
■ Interning creates identical pointers to
pre-existing String
objects whenever possible. This
is to avoid the overhead of unnecessary new object creations.
■ String s1 = “A”; String s2 = “A”; creates just one object via interning, so s1 == s2; here.
■ String s1 = “A”; String s2 = new String(“A”); creates two distinct objects,
because of the
new in
the second statement. s1 == s2 will retun false here.
■
Specifying the intern(
)
method can explicitly make the JVM look for a pre-existing object match from
its String pool to use. But, absent new, all literal strings
and string-valued constant expressions are interned anyway. i.e.
String s = “YES”.intern( ); is the same as String s = "YES";
■ Creating ANY identical-looking variable
contents with new
negates interning. None of them can
have new for
interning to take effect.