String Pool behavior

前端 未结 6 1662
迷失自我
迷失自我 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:24

    Strings are guaranteed to be pooled when you call String.intern() on a string.

    String s1 = "abcd".intern();
    String s2 = "abc";
    s2 += "d";
    s2 = s2.intern();
    s1 == s2 // returns true
    

    When compiler sees a constant it's smart enough to optimize and pool the string literal, i.e.:

    String s1 = "abcd";
    String s2 = "abcd";
    s1 == s2 // returns true
    

    Java Language Specification states:

    Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. 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.

    So in the case of s2 += "d", compiler wasn't as clever as you are and just pooled "d".

提交回复
热议问题