example code:
StringBuffer sb = new StringBuffer("hi");
sb = null;
Question:
will the literal string "hi" somehow stay in memory, even after the StringBuffer has been garbage collected? Or is it just used to create a char array for the StringBuffer and then never put anywhere in memory?
StringBuilder
toStringBuffer
. As for the literalString
, it depends on your version of Java and whether or not it's in theintern
pool. – ImpatientStringBuilder
overStringBuffer
any more. If only used in one thread, the compiler will elide the locking used inStringBuffer
, so it won’t make any difference (as a matter of habit, I useStringBuilder
too). – McculleyStringBuilder
. After all, you have to decide for either. – MarineStringBuffer
will copy the argument passed to its constructor, but does not hold any reference to it, hence, whether it gets garbage collected or not, is entirely irrelevant to the life cycle of the"hi"
string instance. – Marine