Codectionary / Developer documentation / Java

Unicode Code Points and String Length

Understand why String.length can differ from the number of Unicode code points.

What it is and why to use it

Java strings use UTF-16. length counts UTF-16 code units, and a char holds one such unit. A supplementary Unicode character, such as many emoji, uses a surrogate pair of two units. Code-point APIs help avoid splitting such a pair when processing text.

How it works

The example uses Unicode escapes for a supplementary smiling face so the source text is unambiguous. codePointCount counts code points in an index range, while codePoints creates an IntStream of their numeric values. A code point is still not necessarily one user-perceived character: combining marks and emoji sequences can contain several.

Common mistakes and limitations

Do not equate length, code-point count and visible character count. Substring indices are still UTF-16 indices. Text editors, truncation and cursor movement may require grapheme-boundary handling beyond code-point iteration.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

text.length(); text.codePointCount(0, text.length()); text.codePoints();

Examples

Unicode Code Points and String Length

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  public static void main(String[] args) {
    String text = "A\uD83D\uDE00";
    System.out.println(text.length());
    System.out.println(text.codePointCount(0, text.length()));
    text.codePoints().forEach(System.out::println);
  }
}
  1. A uses one UTF-16 unit and the smiling face uses two, so length is 3.
  2. The same text contains two Unicode code points, so codePointCount is 2.
  3. codePoints emits 65 for A and 128512 for the face. These values can be processed without treating each surrogate half as a separate character.
  4. Expected output: 3 2 65 128512

Best practices

  • Choose the text unit that matches the operation.
  • Test text outside ASCII, including combining sequences.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading