java string concatenation and interning

前端 未结 2 1917
一整个雨季
一整个雨季 2020-11-29 12:13

Question 1

String a1 = \"I Love\" + \" Java\";
String a2 = \"I Love \" + \"Java\";
System.out.println( a1 == a2 ); // true

String b1 = \"I Love\";
b1 += \"          


        
2条回答
  •  误落风尘
    2020-11-29 13:03

    From intern() docs

    All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.

    And from JLS 3.10.5

    • Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
      • Strings computed by concatenation at run time are newly created and therefore distinct.

    Your string b1 not actually interned. Hence the difference.

提交回复
热议问题