Why these two similar code snippets lead to different results?
public class Test {
@org.junit.Test
public void test1() {
String s3 = "1" + new String("1");
String s5 = s3.intern();
System.out.println(s5 == s3);
}
@org.junit.Test
public void test2() {
String s3 = "g" + new String("g");
String s5 = s3.intern();
System.out.println(s5 == s3);
}
}
Tried in jdk 1.8.0_144 environment, got these answer (maybe different in jdk6):
false and true
The first snippet should be true in Java8. But more confusingly, If I moved the code into main method, It will result in true.
public class TestWithoutJunit {
public static void main(String[] args) {
String s3 = "1" + new String("1");
String s5 = s3.intern();
System.out.println(s5 == s3);
}
}
I assume this is kind of JUnit optimizing, so I check bytecode, two code snippet inside jUnit and main function remain exactly same.
By the way, my Java version
java version "1.8.0_144" Java(TM) SE Runtime Environment (build 1.8.0_144-b01) Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)