liveBook · Manning

Character boundary

As explained in 100 Java Mistakes and How to Avoid Them

A character boundary is a position in text at which a user-perceived character sequence can be safely divided.

A character boundary is a position where user-perceived text can be divided safely. Java’s char values are not reliable character units: surrogate pairs, combining sequences, and ligature clusters may span multiple char values. Splitting by char index can therefore break an emoji, detach a modifier, or produce malformed user-readable text. section 6.1

Split text by character boundaries

For user-readable text, use BreakIterator rather than substring indexes: BreakIterator iterator = BreakIterator.getCharacterInstance(); iterator.setText(string); iterator.first(); int from = iterator.next(rowLength * rowNumber); int to = iterator.next(rowLength - 1); This recognizes surrogate pairs and keeps combining sequences or emoji modifiers together. section 6.1

Keep text-processing code isolated and prefer dedicated text APIs or ICU4J. For code-point-oriented operations that are not user-character operations, use int-based APIs such as codePointAt and avoid char-centric public interfaces. section 6.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Distinguishes char values, code points, surrogate pairs, combining sequences, and ligature clusters, then recommends boundary-aware APIs.
Examples
Uses emoji, skin-tone modifiers, substring slicing, code-point iteration, and BreakIterator extraction examples.
What it assumes
Assumes Java string familiarity while clarifying why char values do not always represent complete characters.
What you can do after
Apply BreakIterator or code-point APIs to avoid splitting user-perceived characters and mishandling non-BMP text.
How it connects
Connects character boundaries with surrogate pairs, code points, combining characters, ligature clusters, BreakIterator, and ICU4J.

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.