When I define a StringBuffer
variable with new
, this string is not added to the String pool, right?
Now, when I define another String
"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).)