public static void main(String[] args) {
String s1 = new String("aa");
s1.intern();
String s2 = "aa";
System.out.println(s1 == s2);
//wrong in JDK1.6 but true in JDK1.8
String str1 = new String("str") + new String("01");
str1.intern();
String str2 = "str01";
System.out.println(str1 == str2);
}
I run the code above with JDK1.8, and I think I will get two "falses" as result, because in my opinion, it is obvious that s1 & str1 are located in the heap, and s2 & str2 are interned in the string pool, but I got a "false" and a "true". The question comes: what causes the "true"?
Above is the primitive question. Now to identify this question is far from these called duplicated questions, I would like to talk about my new finding: the second part of the code gets a "false" result with JDK1.6 while a "true" result with JDK1.8. Some blogs say the behaviour of intern() has changed after the release of JDK1.7.
If the pool dosen't contain a string equals to this String object, this String object will not added to the pool and a reference to this String object will be added to the pool instead. It means the reference in the pool will be assigned to the string object located somewhere else(like the heap), and next time the initialization of a literal string equals the early one will also be assigned to the string object., which exactly describes the code part2 about the "true" result.
This theory does work on my way to explain result of the code above. But it is obvious that the theory is out of what the intern() doc contains, which is almost the same in JDK6/8 API.
Now the question comes as: Is there any better explaination for the different results of the same code in JDK1.6 & JDK 1.8? Is the theory I mentioned above exactly what truly to happen?