Course contentsShow
← Java
Lesson 538 of 2,87013. The Object Class and Common MethodsFree lesson

StringBuilder for Efficient toString Implementations

Use StringBuilder to construct toString output efficiently when concatenating many fields.

StringBuilder for Efficient toString Implementations

You'll learn why StringBuilder is the professional's choice for building toString output with many fields.

The Problem with String Concatenation

When you override toString using the + operator to join multiple fields, Java creates a new String object for each concatenation. If your class has five fields, that's four intermediate String objects created and immediately discarded:

return "Person[name=" + name + ", age=" + age + ", city=" + city + "]";

Behind the scenes, this generates temporary strings: "Person[name=", then "Person[name=John", then "Person[name=John, age=", and so on. For objects with many fields, this becomes wasteful.

The StringBuilder Solution

StringBuilder is a mutable character sequence designed specifically for building strings efficiently. Think of it like a expandable notepad where you keep adding text without creating a new page each time.

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Person[");
    sb.append("name=").append(name);
    sb.append(", age=").append(age);
    sb.append(", city=").append(city);
    sb.append("]");
    return sb.toString();
}

The append method adds content to the internal buffer without creating new objects. Only at the end do you call toString() to produce the final immutable String.

When It Matters

For classes with just 2–3 fields, simple concatenation is fine—Java optimizes it reasonably well. But for objects with many fields or when toString is called frequently (like in logging frameworks), StringBuilder provides measurably better performance and reduced memory pressure.

Key Takeaway: Use StringBuilder in toString implementations when concatenating many fields—it builds the result efficiently in a single mutable buffer, avoiding the creation of numerous temporary String objects.