The following codes has different results under JDK8 1.8.0_171
@Test
public void test2() {
    String s1 = new String("a") + new String("a");
    s1.intern();
    String s2 = "aa";
    System.out.println(s1 == s2); //true
}
@Test
public void test3() {
    String s1 = new String("1") + new String("1");
    s1.intern();
    String s2 = "11";
    System.out.println(s1 == s2); //false
}
The only difference is the value: "a" instead of "1", the result I get is different. Why is this?
s1.intern() only adds the String referenced by s1 to the String pool if the pool doesn't already contain a String equal to it.
String literals such as "aa" and "11" are always interned, so they will always be == the instance returned by s1.intern().
Therefore, whether or not s1 == s2 returns true depends on whether or not the String pool contained a String equals to s1 before s1.intern() was called.
s1.intern() which is == s2 is not == s1, so System.out.println(s1 == s2) will print false.s1.intern () == s1 == s2, so System.out.println(s1 == s2) will print true.This can change between Java versions, since JDK classes of different versions may contain a different set of String literals, which are automatically interned before your code is executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With