Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Character.charCount — UTF-16 code unit count

Character.charCount(int codePoint) returns the number of char units needed to represent a code point in UTF-16: either 1 or 2. The method does not validate its argument, so its result does not establish that a value is a Unicode code point.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public static int charCount(int codePoint)

Character.charCount(int codePoint) is a static method returning an int. For a valid code point, it determines the number of UTF-16 code units (char): BMP values (U+0000–U+FFFF) use one, while supplementary code points (U+10000–U+10FFFF) use two, forming a surrogate pair.

The exact rule is codePoint >= 0x10000 ? 2 : 1. The method does not validate its argument: it returns 1 for -1 and 2 for 0x110000, although both values are outside the Unicode code point range. When necessary, check the range with Character.isValidCodePoint(codePoint).

Do not confuse the number of char units with the number of code points in text: the method accepts a single int value, not an entire string. A surrogate value such as 0xD800 also produces 1; however, an isolated surrogate does not represent a character.

The example shows an ordinary BMP code point, the boundary between one and two units, a supplementary code point, and two out-of-range arguments. The expected output illustrates both the counting rule and the absence of validation.

Examples

public class Main {
    public static void main(String[] args) {
        int[] values = {0x0041, 0xFFFF, 0x10000, 0x1F600, -1, 0x110000};
        for (int codePoint : values) {
            System.out.println(codePoint + " -> " + Character.charCount(codePoint));
        }
    }
}

Result

65 -> 1
65535 -> 1
65536 -> 2
128512 -> 2
-1 -> 1
1114112 -> 2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources