Library contents

Java String.codePoints

Stream the Unicode code points in a string, combining valid surrogate pairs.

A simple example

String.codePoints

  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😀".codePoints().count());
    }
}
Output
2

Syntax

Java 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.java

Count 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.

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

An ASCII letter, an emoji and a second ASCII letter produce three stream elements.

Advertisements

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.

From the programString note = "OK😀"
Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String note = "OK😀";
        System.out.println(note.codePoints().anyMatch(cp -> cp > 0xffff));
    }
}
Output
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.

GivenNC-17
Worked result5

What to watch for

A grapheme may contain multiple code points. Emoji sequences and combining accents need special handling for cursor movement.

Documentation for String.codePoints