As we know, a java String is immutable and to create mutable String we can use StringBuffer
or StringBuilder
. Now if we have a String in a StringBuilder object and we use the toString()
method of it, will that create another immutable String in the String pool. If so, then how avoid such situation.
Now if we have a String in a StringBuilder object and we use the toString() method of it, will that create another immutable String in the String pool
You don't have a String
in the StringBuilder
. The characters are stored in a char[]
, and when you call toString()
, a new String
is created:
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
That said, creating a new String
doesn't add it to the String
pool, so there's nothing for you to avoid.
our main purpose of using StringBuilder is to avoid immutable Strings
That's not accurate. The main purpose is to avoid creation of multiple String
s as a result of multiple String
concatenations. Using StringBuilder
allows you to perform all the concatenations with a single StringBuilder
instance. If you want a String
representation of the contents of the StringBuilder
, you can't avoid creating one String
instance. However, you don't have to create a String
representation of the StringBuilder
contents (unless you need to pass it to a method that requires a String
).
The implementation of toString()
in those classes look like:
return new String(value, 0, count); // StringBuilder
return new String(toStringCache, true); // StringBuffer
These aren't literals, they're creating a new String
object which will not end up in the string pool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With