Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.codePoints()

Returns a stream of Unicode code points. Unlike chars(), an emoji counts as one character.

Available since: Java 9

Syntax

public IntStream codePoints()

Return value

IntStreamAn IntStream with the code of each character.

Examples

length() counts char units, while codePoints() counts real characters:

void main() {
    String text = "Hi😀";
    IO.println(text.length());
    IO.println(text.codePoints().count());
    IO.println(text.codePointCount(0, text.length()));
}

Output:

4
3
3

Each character and its code as U+XXXX:

void main() {
    "A€😀".codePoints().forEach(cp ->
        IO.println(Character.toString(cp) + " U+" + Integer.toHexString(cp).toUpperCase()));
}

Output:

A U+41
€ U+20AC
😀 U+1F600

Notes

A char holds 16 bits, and characters outside Unicode's basic plane (emoji, rare ideographs) take two char values — a surrogate pair. chars() yields those halves separately, codePoints() yields the whole character. Turn a code back into a string with Character.toString(cp) or new StringBuilder().appendCodePoint(cp). codePointAt(i) returns the code of the character starting at index i.

See also

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.