Java StringBuilder capacity() Method

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

Definition

In Java, sb.capacity() returns the total number of UTF-16 char slots currently allocated inside a StringBuilder's internal buffer before it needs to allocate a larger array.

capacity() is always greater than or equal to length(). When an edit needs more space than capacity(), the builder expands automatically behind the scenes.

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

Syntax

Call capacity() with no arguments to inspect the current buffer size.

Java
StringBuilder empty = new StringBuilder();        // capacity 16
StringBuilder sized = new StringBuilder(64);      // capacity 64
StringBuilder fromStr = new StringBuilder("Hi");  // capacity 2 + 16 = 18
CallWhat it does
new StringBuilder().capacity()Returns 16 (documented default capacity).
new StringBuilder(100).capacity()Returns 100 (exact requested capacity).
new StringBuilder(s).capacity()Returns s.length() + 16.

When text crosses the buffer limit, OpenJDK 8–21 commonly doubles the capacity plus 2 (for example 16 to 34), though the exact growth formula is an implementation detail and may differ across JDK versions or larger requests.

Library declarations
Java
// java.lang.StringBuilder
public int capacity()

Parameters

ParameterDescription
Nonecapacity() takes no parameters.

Return Value

Return ValueDescription
intCurrent internal buffer capacity in UTF-16 char units.

Compare with Similar Methods

Managing StringBuilder length and buffer space:

MethodHow it differs
length()Counts characters actually stored rather than allocated buffer slots.
ensureCapacity(min)Pre-allocates at least min capacity before big builds.
trimToSize()Requests shrinking excess capacity down toward length().
setLength(0)Clears text while preserving existing capacity for loop reuse.

Java Examples

Example 1 — Compare Initial capacity() Across All Three Constructors

Check the starting capacity() and length() of empty, custom-sized, and text-initialized builders.

Java
public class StringBuilderCapacityInit {
    public static void main(String[] args) {
        StringBuilder a = new StringBuilder();
        StringBuilder b = new StringBuilder(40);
        StringBuilder c = new StringBuilder("Java");

        System.out.println("Default:      cap=" + a.capacity() + ", len=" + a.length());
        System.out.println("Custom(40):   cap=" + b.capacity() + ", len=" + b.length());
        System.out.println("From \"Java\":  cap=" + c.capacity() + ", len=" + c.length());
    }
}

How It Works

  1. Default is 16. An empty new StringBuilder() starts with 16 buffer slots and length 0.
  2. Exact custom size. new StringBuilder(40) reserves 40 slots while still holding zero characters.
  3. Text length plus 16. Passing "Java" (length 4) sets initial capacity to 4 + 16 = 20.

Example 2 — Watch capacity() Expand When Appending Past 16 Characters

Append 16 characters to stay inside the initial buffer, then add a 17th character to trigger automatic expansion.

Java
public class StringBuilderCapacityGrow {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("1234567890123456");
        System.out.println("At 16 chars: len=" + sb.length() + ", cap=" + sb.capacity());

        sb.append('7');
        System.out.println("At 17 chars: len=" + sb.length() + ", cap=" + sb.capacity());
        System.out.println("Fits without error? " + (sb.capacity() >= sb.length()));
    }
}

How It Works

  1. Exact fit at 16. Adding 16 digits fills the default buffer completely with no reallocation yet.
  2. Expansion on the 17th char. Standard JDK implementations double 16 plus 2 to reach 34 (exact growth is an implementation detail).
  3. Always large enough. After growth, capacity() stays comfortably above length().

Example 3 — See That delete() and setLength(0) Keep Existing capacity()

Verify that removing characters leaves the allocated buffer ready for reuse.

Java
public class StringBuilderCapacityRetain {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(50);
        sb.append("Temporary log line");
        System.out.println("Filled:  len=" + sb.length() + ", cap=" + sb.capacity());

        sb.setLength(0);
        System.out.println("Cleared: len=" + sb.length() + ", cap=" + sb.capacity());
    }
}

How It Works

  1. Pre-allocated buffer. Starting with capacity 50 leaves room for 32 more characters after "Temporary log line".
  2. Clear text only. setLength(0) resets length to 0 without discarding the 50-char array.
  3. Fast loop reuse. Next appends overwrite the existing buffer without allocating new arrays.

Frequently Asked Questions

16 characters. If you pass a String or CharSequence to the constructor, the initial capacity is that string's length plus 16.
length() is how many characters are stored right now; capacity() is how many characters fit before the internal array must grow.
The specification only guarantees it grows automatically to hold the text. Common JDKs typically grow to 2 * oldCapacity + 2 (so 16 becomes 34), though that exact number is an implementation detail.
No. delete() and setLength(0) reduce length() while keeping capacity() unchanged. Use trimToSize() to request shrinking.
The constructor throws NegativeArraySizeException.

Next: charAt()

Read the single UTF-16 char at a zero-based index without changing the builder.

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

9 people found this page helpful