Difference between addition of String Literals and String objects

后端 未结 4 1898
忘掉有多难
忘掉有多难 2021-01-14 10:23

What is the difference between an addition of String Literal and String Object?

For example

    String s1 =\"hello\";
    String s2 =\"hello1\";
             


        
4条回答
  •  春和景丽
    2021-01-14 11:08

    Because s1 + s2 is not a constant expression, since s1 and s2 are not final, therefore its result is not interned, i.e. another object is created to represent it, so reference comparison produces false.

    JLS 3.10.5 String Literals:

    String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.

    JLS 15.28 Constant Expression:

    A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

    • ...
    • Simple names that refer to constant variables (§4.12.4).

    JLS 4.12.4 defines final variables.

    If you declare s1 and s2 as final, s3 == s5 would be true.

提交回复
热议问题