Strange String pool behavior

后端 未结 4 1909
旧时难觅i
旧时难觅i 2021-01-30 10:02

I\'ve got a question of some strange String pool behavior. I\'m using == to compare equal Strings to find out whether they\'re in the pool or not.

p         


        
4条回答
  •  灰色年华
    2021-01-30 10:51

    "555" + ""
    

    is a compile-time constant, whereas

    giveLiteralString() + ""
    

    isn't. Therefore the former compiles into just the string constant "555" and the latter compiles into the actual method invocation and concatenation, resulting in a fresh String instance.


    Also see JLS §3.10.5 (String Literals):

    Strings computed by concatenation at run time are newly created and therefore distinct.

提交回复
热议问题