In Java, Character.charCount(codePoint) returns how many char values are needed to store the code point in UTF-16: 1 for code points below 0x10000, and 2 for code points from 0x10000 upward, which are stored as a surrogate pair.
Its most common use is stepping through a string one character at a time: read a code point with codePointAt(i), then move i forward by charCount(cp) so you never land on the second half of a pair.
A static method of java.lang.Character (Java 5+): call it on the class, as in Character.charCount(...); you do not need a Character object. No import is needed, because java.lang is always available.
Syntax
Pass an int code point; the result is always 1 or 2.
Java
int a = Character.charCount('A'); // 1
int b = Character.charCount(0xFFFF); // 1, last code point of the BMP
int c = Character.charCount(0x1F600); // 2, an emoji
int d = Character.charCount(0x110000); // 2, even though this is not a valid code point
Call
What it does
i += Character.charCount(cp);
Advance an index past one code point.
Character.charCount(cp) == 2
Will this code point need a surrogate pair?
new char[Character.charCount(cp)]
Allocate exactly enough room for one code point.
Only one overload exists, charCount(int codePoint), added in Java 5 with the rest of the code point API.
Library declarations
Java
// java.lang.Character (since Java 5)
public static int charCount(int codePoint)
Parameters
Parameter
Description
codePoint (int)
The code point to measure.
Return Value
Return Value
Description
1
codePoint is below 0x10000 (this includes negative numbers).
A simple comparison.charCount only asks "is the value at least 0x10000?", so 0x110000 (1114112) gets 2.
Negative numbers. -5 is below 0x10000, so it gets 1, even though no character has a negative code point.
Validate separately.isValidCodePoint rejects both values; use it before trusting a number read from a file or user input.
Frequently Asked Questions
1 if the code point is below 0x10000, otherwise 2. It tells you how many chars the code point occupies in a String.
No. It returns 2 for any value of 0x10000 or more, including invalid ones such as 0x110000. Use isValidCodePoint to check.
for (int i = 0; i < s.length(); ) { int cp = s.codePointAt(i); /* use cp */ i += Character.charCount(cp); }. On Java 8 you can also use s.codePoints().
No. The only possible results are 1 and 2, because UTF-16 never uses more than two chars per code point.
For valid code points, charCount(cp) == 2 exactly when isSupplementaryCodePoint(cp) is true. They differ for invalid values above 0x10FFFF.