Library contents

Java String.codePointCount

Count Unicode code points between two UTF-16 offsets.

A simple example

String.codePointCount

  1. Start with "A😀"
  2. Do this Count Unicode code points
  3. Result 2
The letter and the emoji each contribute one code point.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("A😀".codePointCount(0, 3));
    }
}
Output
2

Syntax

Java syntax
public int codePointCount(int beginIndex, int endIndex)
JDK 21 method signatures (1)
public int codePointCount(int beginIndex, int endIndex)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Count symbols in a student response

A classroom app accepts a short answer containing an emoji between ordinary letters. Count the response in code points before comparing that count with the units used by its underlying string representation.

From the programString response = "A😀B"
Result3
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String response = "A😀B";
        System.out.println(response.codePointCount(0, response.length()));
    }
}
Output
3

The emoji contributes one code point even though it occupies two UTF-16 units.

Advertisements

Inspect an accented name from a form

A student response can combine ordinary letters, accents and emoji. Choose the unit being counted before applying a length limit, because code points and visible symbols do not always line up.

From the programString name = "e\u0301"
Result2
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String name = "e\u0301";
        System.out.println(name.codePointCount(0, name.length()));
    }
}
Output
2

The base letter and the combining accent are two code points displayed together.

Read a parcel sorting code

The depot scans a parcel marked NC-17. This identifier uses only ASCII characters. Count all characters, including the separator, to check the scanner’s length field.

GivenNC-17
Worked result5

What to watch for

Combining marks are counted separately. A code point count can exceed the number of visible grapheme clusters.

Documentation for String.codePointCount