When does StringBuffer adds strings to the String Pool?

前端 未结 4 1553
失恋的感觉
失恋的感觉 2020-12-20 10:19

When I define a StringBuffer variable with new, this string is not added to the String pool, right?

Now, when I define another String

4条回答
  •  温柔的废话
    2020-12-20 10:25

    "XXX" in StrPrev.append("XXX") is a string literal that is interned at class loading time (class loading time of the class that contains the code).

    "XXX" is not added to the pool by the StringBuffer.

    From the JLS section 3.10.5:

    Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances

    From the JLS section 12.5:

    Loading of a class or interface that contains a String literal (§3.10.5) may create a new String object to represent that literal. (This might not occur if the same String has previously been interned (§3.10.5).)

提交回复
热议问题