Java String.codePoints
Stream the Unicode code points in a string, combining valid surrogate pairs.
A simple example
String.codePoints
- 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😀".codePoints().count());
}
}
2
Syntax
public IntStream codePoints()
JDK 21 method signatures (1)
public IntStream codePoints()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCount symbols in a feedback message
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 feedback = "A😀B";
System.out.println(feedback.codePoints().count());
}
}
3
An ASCII letter, an emoji and a second ASCII letter produce three stream elements.
Find a supplementary symbol on a ticket
A feedback or ticket label includes an emoji that needs a full Unicode code point. Inspect the symbol at the right boundary so the value sent to the next component represents the entire character.
class Main {
public static void main(String[] args) throws Exception {
String note = "OK😀";
System.out.println(note.codePoints().anyMatch(cp -> cp > 0xffff));
}
}
true
The emoji has a code point beyond the range of a single char.
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
A grapheme may contain multiple code points. Emoji sequences and combining accents need special handling for cursor movement.