String Pool behavior

前端 未结 6 1623
迷失自我
迷失自我 2021-01-18 02:55

I read this Questions about Java's String pool and understand the basic concept of string pool but still don\'t understand the behavior.

First: it works if you

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-18 03:36

    I think what happens here is: 1. for String s1 = "a" + "bc"; String s2 = "ab" + "c"; Java compiler is smart enough to know that the literal value of s1 and s2 are the same, so the compiler points them to the same literal value in the string pool

    1. for s1 += "d";
      s2 += "d";

    there is no way the compiler know if s1 and s2 would end up being the same value, At runtime, unless you call String.intern(), jvm won't check the string literal pool to see if the value is already there.

提交回复
热议问题