In Java, sb.setLength(newLength) changes the length of a StringBuilder in place. If newLength is shorter than sb.length(), the extra characters at the end are discarded.
If newLength is longer, Java extends the sequence with null characters ('\u0000'). Calling sb.setLength(0) clears a builder quickly so a loop can reuse its buffer without reallocating.
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.setLength(...). No import is needed because java.lang is always visible.
Syntax
Pass a non-negative target length. Because it returns void, call it as a separate statement.
Java
StringBuilder sb = new StringBuilder("Hello, World");
sb.setLength(5); // "Hello" (truncates in place)
sb.setLength(0); // "" (clears text, keeps existing capacity)
Call
What it does
sb.setLength(0)
Clears all text while keeping buffer capacity for reuse.
sb.setLength(sb.length() - 2)
Chops off the last two characters when length() >= 2.
sb.setLength(10)
Grows length to 10, padding new positions with '\u0000'.
When setLength(newLength) shrinks the builder, capacity() does not decrease. Call trimToSize() afterward if you want to release unused buffer space.
Library declarations
Java
// java.lang.StringBuilder
public void setLength(int newLength)
Parameters
Parameter
Description
newLength (int)
Desired length in UTF-16 char units (must be >= 0).
Return Value
Return Value
Description
void
Returns nothing. Cannot be chained.
Compare with Similar Methods
Ways to shorten, clear, or resize a StringBuilder: