When I define a StringBuffer
variable with new
, this string is not added to the String pool, right?
Now, when I define another StringBuffer
but not with new
, I define it as StrPrev.append("XXX")
suddenly it is.(or so says my college teacher). Why is that? What makes this string to suddenly become a string-pool string?
Actually your teacher is referring to
XXX
. which goes to StringPool because all string literals written in java program goes to StringPool while execution...Creating a
StringBuffer
does not create aString
at all.This is totally confused:
When you call
strBuff.append("XXX")
you are NOT defining a newStringBuffer
. You are updating the existingStringBuffer
thatstrBuff
refers to. Specifically, you are adding extra characters to the end of the buffer.You only get a new
String
from theStringBuffer
when you callstrBuff.toString()
.You only add a
String
to the string pool when you callintern()
on theString
. And that only adds the string to the pool if there is not already an equal string in the pool.The String object that represents the literal
"XXX"
is a member of the string pool. But that happens (i.e. the String is added to the pool) when the class is loaded, not when you execute theappend
call.(If you teacher told you that StringBuffer puts strings into the Java string pool, he / she is wrong. But, given your rather garbled description, I suspect that you actually misheard or misunderstood what your teacher really said.)
buf.append("XXX")
followed by buf.toString(), and then returning thestring
to the pool. With the pool in place, only oneStringBuffer
object is ever allocated."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:
From the JLS section 12.5: