Java StringBuilder codePointCount() Method

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

Definition

In Java, sb.codePointCount(beginIndex, endIndex) counts how many Unicode code points sit in the UTF-16 range from beginIndex (inclusive) to endIndex (exclusive) inside a StringBuilder.

While length() counts individual 16-bit char units, codePointCount() treats each valid high-and-low surrogate pair as a single character—essential when enforcing true character limits on text built with emoji.

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

Syntax

Pass inclusive beginIndex and exclusive endIndex (usually 0 and sb.length()).

Java
StringBuilder sb = new StringBuilder("A\\uD83D\\uDE00B");
int units = sb.length();                       // 4
int count = sb.codePointCount(0, sb.length()); // 3
CallWhat it does
sb.codePointCount(0, sb.length())Counts all Unicode code points in the builder.
sb.codePointCount(start, end)Counts code points in a slice from start to end - 1.
sb.length() - countEquals the number of paired surrogate supplementary characters.

Both beginIndex and endIndex are UTF-16 char indexes, and unpaired surrogates count as 1 code point each.

Library declarations
Java
// java.lang.StringBuilder
public int codePointCount(int beginIndex, int endIndex)

Parameters

ParameterDescription
beginIndex (int)Inclusive UTF-16 start index (0 <= beginIndex).
endIndex (int)Exclusive UTF-16 end index (beginIndex <= endIndex <= length()).

Return Value

Return ValueDescription
intNumber of Unicode code points in [beginIndex, endIndex).

Compare with Similar Methods

Measuring characters vs UTF-16 units:

MethodHow it differs
length()Counts raw 16-bit UTF-16 char units (2 per emoji).
offsetByCodePoints(idx, n)Finds the exact UTF-16 index that lies n code points away.
appendCodePoint(cp)Adds 1 code point (which may raise length() by 1 or 2).
String.codePointCount(a, b)Same count on an immutable String.

Java Examples

Example 1 — Compare length() and codePointCount() as Emoji Are Appended

Append an emoji onto "A\\uD83D\\uDE00B" and see how length() grows by 2 while codePointCount() grows by 1.

Java
public class StringBuilderCodePointCountVsLen {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A\uD83D\uDE00B");
        System.out.println("Before: length=" + sb.length() + ", codePoints=" + sb.codePointCount(0, sb.length()));

        sb.appendCodePoint(0x1F680);
        System.out.println("After:  length=" + sb.length() + ", codePoints=" + sb.codePointCount(0, sb.length()));
    }
}

How It Works

  1. Initial gap of 1. "A\\uD83D\\uDE00B" occupies 4 char units for 3 Unicode characters.
  2. Append one supplementary symbol. appendCodePoint(0x1F680) adds a two-char surrogate pair.
  3. Gap grows to 2. length() rises to 6 while codePointCount accurately increments from 3 to 4.

Example 2 — Enforce a Code-Point Budget When Appending

Append incoming code points to a StringBuilder only while its true character count stays under 4.

Java
public class StringBuilderCodePointCountBudget {
    public static void main(String[] args) {
        int[] stream = {'H', 'i', 0x1F600, '!', '?'};
        int maxCodePoints = 4;
        StringBuilder msg = new StringBuilder();

        for (int cp : stream) {
            if (msg.codePointCount(0, msg.length()) < maxCodePoints) {
                msg.appendCodePoint(cp);
            }
        }
        System.out.println("Stored code points: " + msg.codePointCount(0, msg.length()));
        System.out.println("UTF-16 length:      " + msg.length());
        System.out.println("Ends with hex:      0x" + Integer.toHexString(msg.codePointBefore(msg.length())).toUpperCase());
    }
}

How It Works

  1. Measure true character count. Checking codePointCount(0, msg.length()) < 4 stops the emoji from counting as two slots.
  2. Stop at limit. The loop appends 'H', 'i', 0x1F600, and '!' (0x21), skipping '?'.
  3. Different totals. Five UTF-16 units hold the four allowed characters.

Example 3 — Count Subranges and Catch Invalid Bounds

Measure partial ranges of a builder and verify that inverted bounds throw IndexOutOfBoundsException.

Java
public class StringBuilderCodePointCountBounds {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A\uD83D\uDE00B");
        System.out.println("Range [0, 3): " + sb.codePointCount(0, 3));
        System.out.println("Range [1, 3): " + sb.codePointCount(1, 3));
        System.out.println("Empty [2, 2): " + sb.codePointCount(2, 2));

        try {
            sb.codePointCount(3, 1);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Reversed range caught");
        }
    }
}

How It Works

  1. Slice [0, 3). Covers 'A' plus the full surrogate pair at 1..2, counting 2 code points.
  2. Slice [1, 3). Spans only the surrogate pair, returning 1.
  3. Empty and reversed ranges. Same start and end give 0, whereas beginIndex > endIndex throws IndexOutOfBoundsException.

Frequently Asked Questions

length() returns the number of 16-bit UTF-16 char units; codePointCount() returns the number of Unicode code points, counting each surrogate pair as 1.
They are zero-based UTF-16 char indexes, just like substring() and charAt().
It returns 3 (for A, U+1F600, and B), even though length() is 4.
It returns 0, as long as the index is within 0..length().
When beginIndex < 0, endIndex > sb.length(), or beginIndex > endIndex.

Next: delete()

Remove a range of characters from start up to end (end is clamped to length()).

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

13 people found this page helpful