bhylu.com

Advertisements

Java Characters, Code Points and Text Boundaries

A char is a UTF-16 code unit, not always a whole visible character. This distinction matters when an application counts, slices or reverses international text.

Understand the idea

String.length counts UTF-16 code units. A supplementary Unicode code point uses a surrogate pair, so codePointCount may report fewer code points than length. A visible grapheme can itself contain several code points, such as a letter plus a combining mark. Code-point iteration avoids splitting a surrogate pair, but it is not automatically a complete grapheme-aware text editor or a linguistic word-count algorithm.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    public static void main(String[] args) {
        String label = "A\uD83C\uDF31B";
        System.out.println(label.length());
        System.out.println(label.codePointCount(0, label.length()));
        System.out.println(label.offsetByCodePoints(0, 2));
    }
}

Expected output

4
3
3

The seedling symbol occupies two code units between A and B. Advancing two code points from position zero therefore reaches code-unit index three. APIs such as substring still receive code-unit indexes, so choosing boundaries using a code-point-aware operation can matter before slicing.

Check the official Java documentation for detailed contracts and supported options.