Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.length — length in UTF-16 units

String.length() returns the number of UTF-16 code units, not necessarily the number of user-visible characters.

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

Syntax

public int length()
text.length()

String.length is an instance method: text.length() takes no arguments and returns an int. An empty string returns 0.

The method counts UTF-16 code units, or char values. A supplementary Unicode character occupies a surrogate pair, adding 2 to the result. Do not interpret this result as a count of user-visible characters.

Use text.codePointCount(0, text.length()) to count code points. In the example, A and the emoji produce length 3, but two code points.

Examples

public class Main {
    public static void main(String[] args) {
        String text = "A\uD83D\uDE00";
        System.out.println(text.length());
        System.out.println(text.codePointCount(0, text.length()));
        System.out.println("".length());
    }
}

Result

3
2
0

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