The Java Language Specification states that
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(java.lang.Object) method, then the string from the pool is returned
In the following code snippet:
class StringPoolTest {
public static void main(String[] args) {
String first = "string";
String second = new String("string");
String third = "string".intern();
System.out.println(System.identityHashCode(first));
System.out.println(System.identityHashCode(second));
System.out.println(System.identityHashCode(third));
}
}
Output:
989184670
268130470
989184670
I added a String object first to the pool (assigning a String literal to the reference) and explicitly created second using a String constructor. There are now two identical character sequences in the pool.
I wanted to see which one would be returned when calling intern. Since the method hashCode is overridden for the class String, I used System.identityHashCode to see exactly which two String references were the same.
Clearly, intern returned the reference to the object created using a String literal. Why is this so? Are there any rules regarding which reference is returned in the case of multiple identical String objects in the pool?