When I define a StringBuffer variable with new, this string is not added to the String pool, right?
Creating a StringBuffer
does not create a String
at all.
Now, when I define another StringBuffer but not with new, I define it as StrPrev.append("XXX") suddenly it is.
This is totally confused:
When you call strBuff.append("XXX")
you are NOT defining a new StringBuffer
. You are updating the existing StringBuffer
that strBuff
refers to. Specifically, you are adding extra characters to the end of the buffer.
You only get a new String
from the StringBuffer
when you call strBuff.toString()
.
You only add a String
to the string pool when you call intern()
on the String
. 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 the append
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.)
StringBuffer
(which is a way to build strings without having the intermediate result as a string object). – Redcap"
-- that string goes into the literal pool. So"abcd"
and"efgh"
will both be in the string pool, but"abcdefgh"
won't be. – Manatarms