Java StringBuilder setLength() Method

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

Definition

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)
CallWhat 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

ParameterDescription
newLength (int)Desired length in UTF-16 char units (must be >= 0).

Return Value

Return ValueDescription
voidReturns nothing. Cannot be chained.

Compare with Similar Methods

Ways to shorten, clear, or resize a StringBuilder:

MethodHow it differs
delete(0, sb.length())Also clears the builder and returns this if you need chaining.
deleteCharAt(len - 1)Removes the final character and returns this.
ensureCapacity(min)Grows internal buffer capacity without changing length() or padding chars.
length()Reads the current number of stored char units.

Java Examples

Example 1 — Trim Trailing Characters After a Loop

Use setLength(sb.length() - 2) to drop a trailing ", " in one step.

Java
public class StringBuilderSetLengthTrim {
    public static void main(String[] args) {
        String[] cities = {"Rome", "Paris", "Tokyo"};
        StringBuilder sb = new StringBuilder();
        for (String city : cities) {
            sb.append(city).append(", ");
        }
        if (sb.length() >= 2) {
            sb.setLength(sb.length() - 2);
        }
        System.out.println("Cities: " + sb.toString());
    }
}

How It Works

  1. Loop leaves trailing comma. After adding three items with ", ", the builder holds "Rome, Paris, Tokyo, ".
  2. Guard against short buffers. Checking sb.length() >= 2 ensures newLength never goes negative.
  3. Instant O(1) chop. Reducing the length by 2 drops the final space and comma cleanly without shifting anything.

Example 2 — Clear With setLength(0) to Reuse One Builder in a Loop

Reset a single StringBuilder between rows and verify that its allocated capacity() stays intact.

Java
public class StringBuilderSetLengthReuse {
    public static void main(String[] args) {
        StringBuilder row = new StringBuilder(32);
        for (int r = 1; r <= 3; r++) {
            row.setLength(0);
            row.append("Row ").append(r).append(": OK");
            System.out.println(row.toString() + " (cap=" + row.capacity() + ")");
        }
    }
}

How It Works

  1. Allocate once. Creating row outside the loop reserves one 32-char buffer for every line.
  2. Reset before each row. row.setLength(0) discards previous characters in constant time without shrinking capacity.
  3. Stable capacity. Every printed line reuses the exact same 32-char buffer.

Example 3 — Inspect \u0000 Padding Length and Catch Negative Lengths

Grow length with setLength(), verify padding with character codes rather than printing NUL chars, and catch negative arguments.

Java
public class StringBuilderSetLengthPad {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hi");
        sb.setLength(5);
        System.out.println("Expanded length = " + sb.length());
        System.out.println("Char 4 code = " + (int) sb.charAt(4));

        try {
            sb.setLength(-1);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Negative length caught");
        }
    }
}

How It Works

  1. NUL padding applied. Raising length from 2 to 5 fills indexes 2, 3, and 4 with character code 0 ('\u0000').
  2. Inspect safely. Printing length() and (int) sb.charAt(4) verifies the padding without writing raw NUL bytes to stdout.
  3. Negative length rejected. Passing -1 throws IndexOutOfBoundsException.

Frequently Asked Questions

It sets the length of the StringBuilder to 0, effectively clearing all text while keeping the internal capacity so the object can be reused in loops.
It increases length() to newLength and fills the new character positions with NUL characters ('\u0000').
No. It keeps the existing internal char array. Call sb.trimToSize() afterward if you want to release excess capacity.
It throws IndexOutOfBoundsException (specifically StringIndexOutOfBoundsException in current JDKs).
No. setLength() returns void, so chaining on its result fails to compile. Put sb.setLength(0); on its own statement first.

Next: subSequence()

Return a CharSequence slice for [start, end) without modifying the builder.

subSequence() 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.

8 people found this page helpful