Java StringBuilder length() Method

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

Definition

In Java, sb.length() returns the number of char values (16-bit UTF-16 code units) currently stored in a StringBuilder.

It updates automatically after every append, insert, delete, or setLength call. Valid indexes for reading or overwriting characters always run from 0 to sb.length() - 1.

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

Syntax

Call length() with parentheses and no arguments.

Java
StringBuilder sb = new StringBuilder(50);
int emptyLen = sb.length();   // 0 (even though capacity is 50)
sb.append("Java");
int filledLen = sb.length();  // 4
CallWhat it does
sb.length()Current count of stored UTF-16 char units.
sb.length() == 0Checks whether the builder is empty (works on Java 8 and earlier too).
sb.length() > 0Guards delimiter trimming or charAt(sb.length() - 1).

StringBuilder did not add an isEmpty() method until Java 15, so sb.length() == 0 is the universal way to test for an empty builder across all Java versions.

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

Parameters

ParameterDescription
Nonelength() takes no parameters.

Return Value

Return ValueDescription
intThe count of UTF-16 char units currently in the builder (0 or greater).

Compare with Similar Methods

Measuring size, space, and characters:

MethodHow it differs
capacity()Total slots allocated in the internal buffer before resizing.
setLength(newLength)Changes length() directly by truncating or NUL-padding.
codePointCount(0, length())Counts full Unicode characters instead of UTF-16 halves.
trimToSize()Asks the buffer to shrink capacity() down toward length().

Java Examples

Example 1 — Watch length() Change Across Edits vs capacity()

Compare how length() tracks text edits while capacity() reflects buffer allocation.

Java
public class StringBuilderLengthEdits {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(20);
        System.out.println("Start:  len=" + sb.length() + ", cap=" + sb.capacity());

        sb.append("Hello");
        sb.insert(5, ", Java!");
        System.out.println("Added:  len=" + sb.length() + ", cap=" + sb.capacity());

        sb.delete(5, sb.length());
        System.out.println("Cut:    len=" + sb.length() + ", cap=" + sb.capacity());
    }
}

How It Works

  1. Empty with reserved space. new StringBuilder(20) allocates 20 buffer slots while storing zero characters.
  2. Grows length only. Appending 5 chars and inserting 7 brings length() to 12, well inside the existing 20-char capacity.
  3. Deleting leaves capacity alone. Cutting back to "Hello" lowers length() to 5 while capacity remains 20.

Example 2 — Use length() to Avoid Extra Separators

Check sb.length() == 0 to test emptiness on Java 8+ and sb.length() > 0 before adding separators.

Java
public class StringBuilderLengthJoin {
    public static void main(String[] args) {
        String[] words = {"one", "two", "three"};
        StringBuilder sb = new StringBuilder();
        System.out.println("Empty initially? " + (sb.length() == 0));

        for (String w : words) {
            if (sb.length() > 0) {
                sb.append(" | ");
            }
            sb.append(w);
        }
        System.out.println(sb.toString() + " (length=" + sb.length() + ")");
    }
}

How It Works

  1. Portable empty test. sb.length() == 0 works on every Java version from 1.5 through modern releases.
  2. Separator only after first item. On the first pass length is 0, so " | " is skipped.
  3. Exact count. Three words plus two three-char separators equal 3 + 3 + 5 + 6 = 17 chars.

Example 3 — Why length() Counts 2 Units for Supplementary Emoji

Measure a string containing \uD83D\uDE00 with both length() and codePointCount().

Java
public class StringBuilderLengthUtf16 {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A\uD83D\uDE00B");
        System.out.println("length() (UTF-16 units): " + sb.length());
        System.out.println("codePointCount():        " + sb.codePointCount(0, sb.length()));
    }
}

How It Works

  1. Four char slots. 'A' takes 1, \uD83D\uDE00 takes 2 (a surrogate pair), and 'B' takes 1, so length() returns 4.
  2. Three logical characters. codePointCount(0, sb.length()) combines the surrogate pair and returns 3.
  3. Use length() for indexes. Methods like charAt and substring always expect UTF-16 indexes based on length().

Frequently Asked Questions

length() is how many characters are actually stored right now; capacity() is how many characters the internal array can hold before allocating more space.
Check sb.length() == 0. (The isEmpty() method on CharSequence/StringBuilder was only added in Java 15.)
length() with parentheses, because it is a method on StringBuilder (just like String), unlike array.length which is a field.
Java stores characters as 16-bit UTF-16 char units, and supplementary characters above U+FFFF require a two-char surrogate pair.
No. Whenever an edit needs more characters than capacity(), StringBuilder automatically grows capacity() first.

Next: offsetByCodePoints()

Move a UTF-16 index forward or backward by a given number of Unicode code points.

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

12 people found this page helpful