java – Will the toString() method of StringBuilder or StringBuffer create a new immutable String?

java – Will the toString() method of StringBuilder or StringBuffer create a new immutable String?

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 dont 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, dont share the array
    return new String(value, 0, count);
}

That said, creating a new String doesnt add it to the String pool, so theres nothing for you to avoid.

our main purpose of using StringBuilder is to avoid immutable Strings

Thats not accurate. The main purpose is to avoid creation of multiple Strings 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 cant avoid creating one String instance. However, you dont 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 arent literals, theyre creating a new String object which will not end up in the string pool.

java – Will the toString() method of StringBuilder or StringBuffer create a new immutable String?

YES , it will create another instance of an string when you call toString() on StringBuilder Object

If you want to avoid that, you can just modify the return type of the method to StringBuilder instead of String, if that is the case, and can progress with the StringBuilder Object

Leave a Reply

Your email address will not be published. Required fields are marked *