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.
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
Parameter
Description
None
trimToSize() takes no parameters.
Return Value
Return Value
Description
void
Returns nothing; only internal buffer storage may shrink.
Trim mid-way. Shrinking after "Hi" leaves length at 2 with capacity still at least 2.
Still mutable. Appending ", Java Developer!" grows the internal array automatically again.
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.