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
Call
What 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() - count
Equals 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
Parameter
Description
beginIndex (int)
Inclusive UTF-16 start index (0 <= beginIndex).
endIndex (int)
Exclusive UTF-16 end index (beginIndex <= endIndex <= length()).
Return Value
Return Value
Description
int
Number of Unicode code points in [beginIndex, endIndex).
Range [0, 3): 2
Range [1, 3): 1
Empty [2, 2): 0
Reversed range caught
How It Works
Slice [0, 3). Covers 'A' plus the full surrogate pair at 1..2, counting 2 code points.
Slice [1, 3). Spans only the surrogate pair, returning 1.
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.