Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does new String() + new String() return different results under JDK8

Tags:

java

string

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?

like image 685
anan.kun Avatar asked Dec 31 '22 15:12

anan.kun


1 Answers

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.

  • If it did, s1.intern() which is == s2 is not == s1, so System.out.println(s1 == s2) will print false.
  • If it did not, 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.

like image 65
Eran Avatar answered Feb 06 '23 17:02

Eran