The answer by Petr Janeček is almost certainly correct (+1 there).
Really proving it is hard, because much of the string pool resides in the JVM itself, and one could hardly access it without a tweaked VM.
But here is some more evidence:
public class TestInternEx
{
public static void main(String[] args)
{
char[] c1 = { 'a', 'b', 'h', 'i' };
String s1 = new String(c1);
String s1i = s1.intern();
String s1s = "abhi";
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s1i));
System.out.println(System.identityHashCode(s1s));
System.out.println(s1 == s1s);// true
char[] cj =
{ 'j', 'a', 'v', 'a' };
String sj = new String(cj);
String sji = sj.intern();
String sjs = "java";
System.out.println(System.identityHashCode(sj));
System.out.println(System.identityHashCode(sji));
System.out.println(System.identityHashCode(sjs));
System.out.println(sj == sjs);// false
char[] Cj = { 'J', 'A', 'V', 'A' };
String Sj = new String(Cj);
String Sji = Sj.intern();
String Sjs = "JAVA";
System.out.println(System.identityHashCode(Sj));
System.out.println(System.identityHashCode(Sji));
System.out.println(System.identityHashCode(Sjs));
System.out.println(Sj == Sjs);// true
char[] ct =
{ 't', 'r', 'u', 'e' };
String st = new String(ct);
String sti = st.intern();
String sts = "true";
System.out.println(System.identityHashCode(st));
System.out.println(System.identityHashCode(sti));
System.out.println(System.identityHashCode(sts));
System.out.println(st == sts);// false
}
}
The program prints, for each string, the identity hash code of
- the string that is created with
new String
- the string that is returned by
String#intern
- the string that is given as a literal
The output is along the lines of this:
366712642
366712642
366712642
true
1829164700
2018699554
2018699554
false
1311053135
1311053135
1311053135
true
118352462
1550089733
1550089733
false
One can see that for the String "java"
, the hash code of the new String
is different from that of the string literal, but that the latter is the same as the one for the result of calling String#intern
- which means that String#intern
indeed returned a string that is deeply identical to the literal itself.
I also added the String "true"
as another test case. It shows the same behavior, because one can assume that the string true
will already have appeared before when bootstrapping the VM.
intern()
. Re-read the docs, assign the return value to your original reference, and you'll see it works as you expect. Also, please do not ever depend onintern()
. – KimuraString.intern
is not avoid
method, it returns aString
. You are ignoring the return value. Read the documentation. Do not ignore return values. – Songwriters1
orsj
orsj1
anywhere. – Consciousnew String()
always return a new object. – Kimura