Java StringBuilder trimToSize() Method

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

Definition

In Java, sb.trimToSize() asks a StringBuilder to reduce the size of its internal storage array so unused buffer capacity can be reclaimed.

Think of it as a memory-saving hint rather than a strict mandate: it returns void, never alters length() or the text, and usually shrinks capacity() down to length() in standard JDK implementations.

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.trimToSize(...). No import is needed because java.lang is always visible.

Syntax

Call trimToSize() with no arguments after a builder finishes growing or shrinking.

Java
StringBuilder sb = new StringBuilder(200);
sb.append("Java");
sb.trimToSize();   // requests shrinking capacity toward 4 (returns void)
CallWhat it does
sb.trimToSize()Attempts to release unused buffer slots.
sb.capacity() >= sb.length()Always guaranteed true after trimming.
sb.toString()Also yields a compact immutable copy when you no longer need mutability.

Because trimToSize() returns void, it cannot be chained. If you will keep appending right afterward, trimming only forces an extra array copy on the next append.

Library declarations
Java
// java.lang.StringBuilder
public void trimToSize()

Parameters

ParameterDescription
NonetrimToSize() takes no parameters.

Return Value

Return ValueDescription
voidReturns nothing; only internal buffer storage may shrink.

Compare with Similar Methods

Capacity and memory helpers:

MethodHow it differs
capacity()Inspects the current buffer allocation.
ensureCapacity(min)Opposite direction: reserves space ahead of time.
toString()Converts the builder into an exact-sized immutable String.
ArrayList.trimToSize()Same storage-trimming hint for ArrayList.

Java Examples

Example 1 — Shrink Excess Buffer Space After Building Short Text

Create a 200-char builder, store four characters, call trimToSize(), and check invariants plus typical capacity reduction.

Java
public class StringBuilderTrimBasic {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(200);
        sb.append("Java");
        System.out.println("Before trim: len=" + sb.length() + ", cap=" + sb.capacity());

        sb.trimToSize();
        System.out.println("After length: " + sb.length());
        System.out.println("cap >= len?   " + (sb.capacity() >= sb.length()));
        System.out.println("cap == len (typical, not guaranteed)? " + (sb.capacity() == sb.length()));
    }
}

How It Works

  1. Large unused gap. Before trimming, 196 of the 200 reserved slots sit empty.
  2. Content and length preserved. Trimming never loses characters, leaving length() at 4.
  3. Guaranteed vs typical check. capacity() >= length() is guaranteed; capacity() == length() holds on standard OpenJDK builds as typical behavior.

Example 2 — Release Unused Space After Deleting Most of a Builder

Build a long line, delete almost everything, call trimToSize(), and verify text integrity.

Java
public class StringBuilderTrimAfterDelete {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Start-0123456789-0123456789-End");
        int capBefore = sb.capacity();
        sb.delete(5, sb.length());

        sb.trimToSize();
        System.out.println("Text preserved: " + sb.toString());
        System.out.println("Length:         " + sb.length());
        System.out.println("cap >= len?     " + (sb.capacity() >= sb.length()));
        System.out.println("Not larger?     " + (sb.capacity() <= capBefore));
    }
}

How It Works

  1. Delete keeps old buffer. Deleting indexes 5..31 leaves only "Start" inside a buffer sized at 47.
  2. Request shrinkage. trimToSize() asks the JVM to free the excess array space.
  3. Text intact. sb.toString() still equals "Start" and buffer size stays within bounds.

Example 3 — Keep Using a StringBuilder After trimToSize()

Show that trimming does not lock a builder—future append() calls still grow the buffer automatically.

Java
public class StringBuilderTrimReuse {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(100);
        sb.append("Hi");
        sb.trimToSize();
        System.out.println("Trimmed len=" + sb.length() + ", valid? " + (sb.capacity() >= sb.length()));

        sb.append(", Java Developer!");
        System.out.println("Appended:   " + sb.toString());
        System.out.println("Grew len=" + sb.length() + ", valid? " + (sb.capacity() >= sb.length()));
    }
}

How It Works

  1. Trim mid-way. Shrinking after "Hi" leaves length at 2 with capacity still at least 2.
  2. Still mutable. Appending ", Java Developer!" grows the internal array automatically again.
  3. Invariants hold. Length advances to 19 and capacity automatically expands to hold every character.

Frequently Asked Questions

No. trimToSize() is a storage-reduction attempt/hint. In practice on OpenJDK capacity() usually shrinks to length(), though the spec does not force every implementation to match exact equality.
No. Only the unused buffer space may shrink; stored characters and length() remain identical.
Yes. The builder stays mutable and grows automatically again when more characters are added.
No. trimToSize() returns void, so it must stand on its own line.
Avoid calling it inside loops or right before more appends, because growing the buffer back requires another array allocation and copy.

Back to the method index

See all 24 StringBuilder method guides grouped by what they do.

Method index →

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.

12 people found this page helpful