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

  • A+
Category:Languages

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: