class Test {
public static void main(String...args) {
String s1 = \"Good\";
s1 = s1 + \"morning\";
System.out.println(s1.intern());
Let's omit unnecessary details from the example:
class Test {
public static void main(String... args) {
String s1 = "Good";
s1 = s1 + "morning";
System.out.println(s1 == s1.intern()); // Prints true for jdk7, false - for jdk6.
}
}
Let's consider String#intern as a black box. Based on a few test cases run, I would conclude that implementation is as following:
Java 6:
if the pool contains object equals to this, then return reference to that object,
else create new string (equal to this), put to the pool, and return reference to that created instance.
Java 7:
if the pool contains object equals to this, then return reference to that object,
else put this to the pool, and return this.
Neither Java 6 nor Java 7 breaks the contract of the method.
It seems that new intern method behavior was a result of the fix of this bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6962931.