Java String.codePointCount
Count Unicode code points between two UTF-16 offsets.
A simple example
String.codePointCount
- Start with "A😀"
- Do this Count Unicode code points
- Result 2
class Main {
public static void main(String[] args) throws Exception {
System.out.println("A😀".codePointCount(0, 3));
}
}
2
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.javaCount 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.
class Main {
public static void main(String[] args) throws Exception {
String response = "A😀B";
System.out.println(response.codePointCount(0, response.length()));
}
}
3
The emoji contributes one code point even though it occupies two UTF-16 units.
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.
class Main {
public static void main(String[] args) throws Exception {
String name = "e\u0301";
System.out.println(name.codePointCount(0, name.length()));
}
}
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.
What to watch for
Combining marks are counted separately. A code point count can exceed the number of visible grapheme clusters.