Sub topic 12
Unicode Code Points and Text Boundaries
Java strings can hold text from many languages, as well as symbols and emoji. But one visible character does not always take up one position in a Java string.
This matters when you count, inspect, or extract text. A cut at the wrong position can split an emoji or separate an accent from its letter.
Three ways to count text
Unicode is a standard that gives numbers to characters and other parts of text. A Unicode code point is one of those numbers. For example, the code point for A is written as U+0041.
Java uses UTF-16 positions when it counts and indexes a string. UTF-16 is a way to represent Unicode text using 16-bit pieces called code units. An index is the position of a code unit, starting at zero.
A Java char holds one UTF-16 code unit. Some code points fit in one code unit. Others need two. A code point above U+FFFF, such as U+1F600 for 😀, uses two code units. Those two units form a surrogate pair.
A visible character can also contain more than one code point. For example, e followed by a combining acute accent appears as é. A combining accent is a mark that attaches to a nearby character.
So there are three different things you might count:
- UTF-16 code units: what
String.length()counts. - Unicode code points: what
codePointCount()counts. - Visible text units: what a reader may see as single characters.
A string with an emoji and an accent
Consider this string:
String text = "A\uD83D\uDE00e\u0301";The \u sequences are Java escape sequences for specific char values. Here, \uD83D and \uDE00 form the emoji’s surrogate pair. The final \u0301 is a combining acute accent.
The text looks like A😀é. Its UTF-16 positions are:
| Index | Code unit | Role |
|---|---|---|
| 0 | `A` | The letter `A` |
| 1 | `\uD83D` | First half of the emoji’s surrogate pair |
| 2 | `\uDE00` | Second half of the emoji’s surrogate pair |
| 3 | `e` | The letter `e` |
| 4 | `\u0301` | Combining acute accent |
This string has five UTF-16 code units, four code points, and typically three visible characters: A, 😀, and é.
The emoji is one code point but takes two code units. The accented é uses two code points but is usually seen as one character.
Count and inspect code points
The following program counts the code units and code points. It then visits each code point without stepping into the middle of the emoji.
Save it as UnicodeText.java:
class UnicodeText {
public static void main(String[] args) {
String text = "A\uD83D\uDE00e\u0301";
System.out.println("Code units: " + text.length());
System.out.println(
"Code points: " + text.codePointCount(0, text.length())
);
for (int index = 0; index < text.length();) {
int codePoint = text.codePointAt(index);
System.out.printf("Index %d: U+%04X%n", index, codePoint);
index += Character.charCount(codePoint);
}
int faceStart = text.offsetByCodePoints(0, 1);
int faceEnd = text.offsetByCodePoints(0, 2);
String face = text.substring(faceStart, faceEnd);
System.out.println("Face starts at index: " + faceStart);
System.out.println("Face ends at index: " + faceEnd);
System.out.println("Face code units: " + face.length());
}
}Compile and run it:
javac UnicodeText.java
java UnicodeTextThe output is:
Code units: 5
Code points: 4
Index 0: U+0041
Index 1: U+1F600
Index 3: U+0065
Index 4: U+0301
Face starts at index: 1
Face ends at index: 3
Face code units: 2How the loop moves
codePointAt(index) reads the code point starting at a UTF-16 index. It returns an int, which can hold the number for a code point.
Character.charCount(codePoint) returns the number of code units needed for that code point: one or two. The loop adds that number to index.
For the emoji, the loop reads the pair at indexes 1 and 2. It then moves directly to index 3. A loop that always adds one would visit each code unit, not each code point.
The values printed after U+ use hexadecimal, a way to write numbers using the digits 0 through 9 and the letters A through F.
Extract at code point boundaries
A text boundary is a position between parts of text where you can make a cut. A code point boundary is a position before or after a complete code point.
The example uses offsetByCodePoints(0, 1) to move one code point from UTF-16 index 0. The result is index 1, the start of the emoji. Moving two code points from index 0 gives index 3, the position after the emoji.
The call substring(faceStart, faceEnd) then extracts the emoji. The start index is included, and the end index is excluded. Although the result is one code point, its length() is still two.
Use a known code point boundary as the starting index for offsetByCodePoints(). Starting in the middle of a surrogate pair does not fix that position. Also, moving past the start or end of the string causes an IndexOutOfBoundsException.
Avoid cutting between the two units of a surrogate pair. For example, text.substring(1, 2) keeps only the first half of the emoji, not the complete emoji.
Code points are not always visible characters
A code point boundary can still be the wrong place to cut visible text. In the example, the boundary between e and the accent is a valid code point boundary. But cutting there separates the accent from the letter.
A grapheme cluster is a sequence of code points treated as one unit of visible text. The e and its combining accent form a grapheme cluster. Some emoji also form a cluster from multiple code points.
This matters for tasks such as moving a cursor, selecting text, or limiting what a user can type. Counting code points may be enough for some rules, but it does not always match what a person sees.
Java’s BreakIterator.getCharacterInstance() can help find character boundaries. Its behavior can depend on the Java version, and it may not keep every modern emoji sequence together. If your task needs strict grapheme-cluster handling, consider a Unicode-aware library such as ICU4J. Test it with the languages and emoji your program needs to support.
Practice
Exercise
A string contains only 😀. What do length() and codePointCount(0, length()) return?
Show answer
length() returns 2 because the emoji uses two UTF-16 code units. codePointCount(0, length()) returns 1.
Exercise
Why does the example loop add Character.charCount(codePoint) instead of always adding 1?
Show answer
A code point may use two UTF-16 code units. The loop must move past both units before reading the next code point.
Exercise
Is the boundary between e and its combining accent a safe place to cut if you want to keep visible characters together?
Show answer
No. It is a code point boundary, but the letter and accent form one grapheme cluster.