class Test {
public static void main(String...args) {
String s1 = "Good";
s1 = s1 + "morning";
System.out.println(s1.intern());
String s2 = "Goodmorning";
if (s1 == s2) {
System.out.println("both are equal");
}
}
}
This code produces different outputs in Java 6 and Java 7.
In Java 6 the s1==s2 condition returns false and in Java 7 the s1==s2 returns true. Why?
Why does this program produces different output in Java 6 and Java 7?
It seems that JDK7 process intern in a different way as before.
I tested it with build 1.7.0-b147 and got “both are equal”, but when executing it (same bytecode) with 1,6.0_24 I do not get the message.
It also depends where the
String b2 =...line is located in the source code. The following code also does not output the message:it seems like
internafter not finding the String in its pool of strings, inserts the actual instance s1 into the pool. The JVM is using that pool when s2 is created, so it gets the same reference as s1 back. On the other side, if s2 is created first, that reference is stored into the pool.This can be a result of moving the interned Strings out from the permanent generation of the Java heap.
Found here: Important RFEs Addressed in JDK 7
Not sure if that is a bug and from which version… The JLS 3.10.5 states
so the question is how pre-existing is interpreted, compile-time or execute-time: is “Goodmorning” pre-existing or not?
I prefer the way it WAS implemented before 7…