liveBook · Manning

codePointAt

As explained in 100 Java Mistakes and How to Avoid Them

codePointAt is a Java String API method that returns the Unicode code point beginning at a specified UTF-16 char index.

codePointAt returns the Unicode code point beginning at a specified UTF-16 char index. It avoids treating every char value as a complete character, which fails for supplementary characters encoded as surrogate pairs. section 6.1

Avoid charAt for Unicode-aware checks

A digit check based on charAt can reject a supplementary digit: static boolean startsWithDigit(String str) { return !str.isEmpty() && Character.isDigit(str.charAt(0)); } Use codePointAt instead: static boolean startsWithDigit(String str) { return !str.isEmpty() && Character.isDigit(str.codePointAt(0)); } The int result selects Character.isDigit(int), allowing digits outside the Basic Multilingual Plane. section 6.1

Use code-point-centered APIs when strings may contain arbitrary Unicode characters:

  • Prefer codePointAt(), codePointBefore(), codePointCount(), and codePoints() over char-centered processing. section 6.1
  • Account for the performance cost: locating the nth code point may require traversing earlier UTF-16 units to detect surrogate pairs. section 6.1
String part = string.codePoints().skip(rowNumber * rowLength)
       .limit(rowLength)
       .collect(StringBuilder::new,
                StringBuilder::appendCodePoint,
                StringBuilder::append)
       .toString();

Shows how to traverse code points and rebuild a string with appendCodePoint rather than slicing by char positions. section 6.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains surrogate-pair failures, corrected overload selection, alternative APIs, and traversal costs without detailing implementation internals.
Examples
Demonstrates supplementary digits, Chinese names, startsWithDigit, and code-point-based string extraction.
What you can do after
Apply codePointAt and related Java APIs when char-based processing could split or misclassify supplementary characters.
How it connects
Connects UTF-16, surrogate pairs, Unicode code points, Character.isDigit, StringBuilder, and the Stream API.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.