Java StringBuilder toString() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.lang.StringBuilder

Definition

In Java, sb.toString() builds and returns a new immutable String containing a copy of the characters currently in the StringBuilder.

Because StringBuilder is not a subclass of String, calling toString() is the standard final step when returning built text, comparing content with equals(), or storing a value as a key.

An instance method of the java.lang.StringBuilder class (since Java 1.5, JDK 1.5): a final, mutable sequence of UTF-16 characters that is not thread-safe. Call it on an existing builder, as in sb.toString(...). No import is needed because java.lang is always visible.

Syntax

Call toString() with no arguments when you are ready for an immutable String.

Java
StringBuilder sb = new StringBuilder("Hello").append(", Java");
String result = sb.toString();   // "Hello, Java"
CallWhat it does
sb.toString()Returns a new String snapshot of the builder.
sb1.toString().equals(sb2.toString())Compares two builders by text content safely.
return sb.toString();Typical ending of a helper method returning String.

Calling System.out.println(sb) or concatenating "" + sb invokes sb.toString() implicitly, while passing sb directly to a method expecting String requires an explicit sb.toString().

Library declarations
Java
// java.lang.StringBuilder
public String toString()

Parameters

ParameterDescription
NonetoString() takes no parameters.

Return Value

Return ValueDescription
StringA new immutable String containing the builder's current characters.

Compare with Similar Methods

Converting and comparing StringBuilder text:

MethodHow it differs
substring(start, end)Creates a String from only a subrange rather than the whole builder.
String.equals(other)Compares the converted String values character by character.
String.contentEquals(cs)Compares a String directly against a StringBuilder without allocating a String.
subSequence(start, end)Returns a slice as a CharSequence.

Java Examples

Example 1 — Avoid the sb1.equals(sb2) Trap With toString()

See why two separate builders with the same text fail equals() until converted via toString().

Java
public class StringBuilderToStringEquals {
    public static void main(String[] args) {
        StringBuilder a = new StringBuilder("Code").append("ToFun");
        StringBuilder b = new StringBuilder("CodeToFun");

        System.out.println("a.equals(b):                  " + a.equals(b));
        System.out.println("a.toString().equals(b):       " + a.toString().equals(b.toString()));
        System.out.println("b.toString().contentEquals(a): " + b.toString().contentEquals(a));
    }
}

How It Works

  1. Identity check fails. a and b are distinct objects, so Object.equals returns false.
  2. Convert both to String. Calling toString().equals(...) compares actual characters and prints true.
  3. Compare directly via contentEquals. A String can also inspect a StringBuilder directly through contentEquals(CharSequence).

Example 2 — Freeze an Immutable Snapshot Before Further Edits

Verify that calling toString() captures a copy that ignores later append() or reverse() changes.

Java
public class StringBuilderToStringSnapshot {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Draft");
        String v1 = sb.toString();

        sb.append("-Final").reverse();
        String v2 = sb.toString();

        System.out.println("v1: " + v1);
        System.out.println("v2: " + v2);
    }
}

How It Works

  1. Capture first version. v1 receives an independent immutable String copy holding "Draft".
  2. Continue editing builder. Appending "-Final" and reversing only alters sb.
  3. Snapshots stay separate. v1 remains Draft while v2 holds the reversed text.

Example 3 — Convert to String Before Using as a HashMap Key

Build a lookup key in a StringBuilder and freeze it with toString() so HashMap lookup works reliably.

Java
import java.util.HashMap;
import java.util.Map;

public class StringBuilderToStringMapKey {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();

        StringBuilder keyBuilder = new StringBuilder("team").append('-').append(1);
        scores.put(keyBuilder.toString(), 95);

        String lookup = "team-1";
        System.out.println("Score for team-1: " + scores.get(lookup));
    }
}

How It Works

  1. Assemble key cleanly. keyBuilder joins "team", '-', and 1 without intermediate strings.
  2. Freeze to immutable String. Passing keyBuilder.toString() puts a stable String key with proper hashCode() and equals() into the map.
  3. Lookup succeeds. Searching with literal "team-1" matches the stored key and prints 95.

Frequently Asked Questions

StringBuilder inherits Object.equals(), which checks object identity instead of characters. Compare sb1.toString().equals(sb2.toString()) (or compareTo == 0 in Java 11+).
No. It returns a new String copy and leaves the StringBuilder intact.
No. String objects are immutable and independent of subsequent StringBuilder edits.
No, println calls String.valueOf(sb) which invokes toString() automatically. You only need toString() when passing to a String parameter or comparing Strings.
StringBuilder uses identity hashCode/equals and is mutable. Converting to String provides value-based hashing and guarantees the key cannot change afterward.

Next: trimToSize()

Ask the builder to shrink its internal storage buffer down toward length().

trimToSize() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful