Search code examples
javastring-interning

String.intern is it the same just copy an object reference in Java?


Is doing:

String a = new String();
String b = a;

and doing:

String a = new String();
String b = a.intern();

is the same ?

Actually, the reference are all the same if I test:

String a = new String("te");
String b = a.intern();
String c = a;
String d = "t" + "e";
System.out.print(a.equals(b));
System.out.print(b.equals(c));
System.out.print(a.equals(d));

Cause the String will ever be in the String pool ?


Solution

  • Your equals tests aren't checking for references - they're checking for string equality. You should be using == to check the references for identity. Effectively, you're making the common rookie Java mistake in reverse - usually people use == when they should be using equals. In this particular case, all of those will print false, because there are two String objects involved (the string from the constant pool, and the new string created in the first line). If we call these #1 and #2 respectively, we end up with:

    a = #2 // Explicit call to string constructor
    b = #1 // intern will return reference to constant pool instance
    c = #2 // Direct assignment
    d = #1 // Equivalent string constant, so reference to constant pool instance
    

    However, you may find this interesting:

    String a = "te";
    String b = a.intern();
    String c = "t" + "e";
    System.out.println(a == b); // true
    System.out.println(a == c); // true
    

    "te" and "t" + "e" are equal constant string expressions, so end up as references to a single string, and calling intern on a string already in the literal pool won't have any effect.