Java StringBuilder ensureCapacity() Method

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

Definition

In Java, sb.ensureCapacity(minimumCapacity) makes sure a StringBuilder's internal buffer can hold at least minimumCapacity UTF-16 char units before it needs to grow again.

Calling it ahead of a large build can prevent repeated array copies as text grows. Like setLength(), ensureCapacity() returns void and never changes length() or the stored characters.

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

Syntax

Pass the minimum number of char slots you want reserved as a standalone statement.

Java
StringBuilder sb = new StringBuilder();
sb.ensureCapacity(1000);   // guarantees capacity() >= 1000; length() stays 0
CallWhat it does
sb.ensureCapacity(500)Ensures capacity() >= 500 without adding characters.
new StringBuilder(500)Sets the starting capacity directly at creation time.
sb.ensureCapacity(0)No-op: zero or negative values are ignored safely.

If minimumCapacity exceeds the current capacity, Java grows the buffer to at least the larger of minimumCapacity and its automatic growth target (typically 2 * oldCapacity + 2, an implementation detail).

Library declarations
Java
// java.lang.StringBuilder
public void ensureCapacity(int minimumCapacity)

Parameters

ParameterDescription
minimumCapacity (int)Desired minimum buffer capacity in UTF-16 char units.

Return Value

Return ValueDescription
voidReturns nothing. Cannot be chained.

Compare with Similar Methods

Controlling StringBuilder capacity:

MethodHow it differs
capacity()Reads the current allocated capacity.
trimToSize()Opposite hint: asks the builder to shrink excess space afterward.
setLength(n)Changes actual character length() (and pads with \u0000 if growing).
ArrayList.ensureCapacity(n)Same pre-allocation idea for lists.

Java Examples

Example 1 — Preallocate Room Without Changing length()

Verify that ensureCapacity(500) raises capacity() to at least 500 while leaving the builder empty.

Java
public class StringBuilderEnsureCapBasic {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        System.out.println("Before >= 500? " + (sb.capacity() >= 500));

        sb.ensureCapacity(500);
        System.out.println("After >= 500?  " + (sb.capacity() >= 500));
        System.out.println("Length stays:  " + sb.length());
    }
}

How It Works

  1. Starts small. A default builder begins with capacity 16, well below 500.
  2. Guaranteed minimum. After ensureCapacity(500), capacity() >= 500 is guaranteed to be true.
  3. Zero characters added. Unlike setLength(), ensureCapacity() keeps length() at 0.

Example 2 — Reserve Capacity Before Appending a Known Batch

Estimate total characters before appending 50 rows so the loop avoids intermediate buffer resizes.

Java
public class StringBuilderEnsureCapLoop {
    public static void main(String[] args) {
        StringBuilder report = new StringBuilder();
        int rows = 50;
        report.ensureCapacity(rows * 8);

        for (int i = 1; i <= rows; i++) {
            report.append("Row ").append(i).append('\n');
        }
        System.out.println("Capacity >= 400? " + (report.capacity() >= 400));
        System.out.println("Final length:    " + report.length());
    }
}

How It Works

  1. Reserve once up front. Multiplying 50 rows by 8 chars reserves at least 400 slots before the loop begins.
  2. Append smoothly. All 50 lines fit in 341 characters without reallocating mid-loop.
  3. Result unchanged. Output text is identical with or without ensureCapacity(); only extra copying is avoided.

Example 3 — Small or Negative Arguments Are Safe No-Ops

Confirm that passing 0, -10, or a number smaller than current capacity does not shrink or throw.

Java
public class StringBuilderEnsureCapNoop {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");
        int initialCap = sb.capacity();

        sb.ensureCapacity(-10);
        sb.ensureCapacity(0);
        sb.ensureCapacity(5);

        System.out.println("Unchanged capacity? " + (sb.capacity() == initialCap));
        System.out.println("Content: " + sb.toString());
    }
}

How It Works

  1. Initial room is 21. "Hello" starts with 5 + 16 = 21 buffer slots.
  2. Smaller values ignored. Calling ensureCapacity with -10, 0, or 5 leaves the buffer completely untouched.
  3. No shrinking, no error. Unlike constructors, negative arguments do not throw.

Frequently Asked Questions

No. It only affects the internal buffer size (capacity); length() and characters stay unchanged.
No. ensureCapacity() returns void, so it must be written as its own statement.
Use the constructor when creating a brand-new builder whose approximate size you already know. Use ensureCapacity() on an existing builder before a large append batch.
Nothing. It safely ignores non-positive numbers and never shrinks an already-large buffer.
It guarantees at least minimumCapacity (in practice, OpenJDK picks the larger of minimumCapacity and 2 * oldCapacity + 2, which is an implementation detail).

Next: getChars()

Copy a slice of characters from the builder directly into an existing char[] array.

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

7 people found this page helpful