Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 641
sam Avatar asked May 01 '18 06:05

sam


2 Answers

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 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 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).

like image 126
Eran Avatar answered Oct 26 '22 23:10

Eran


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.

like image 24
ernest_k Avatar answered Oct 27 '22 01:10

ernest_k