Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Strings and Unicode

Strings and Unicode: String is an immutable sequence of UTF-16 code units; length counts code units, so a supplementary character occupies two chars but one code point.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

strings

String is an immutable sequence of UTF-16 code units; length counts code units, so a supplementary character occupies two chars but one code point.

Use equals rather than == for content, Locale.ROOT for protocol case normalization, and StringBuilder for repeated concatenation.

toLowerCase without a Locale depends on the default locale; visually equal text can have different Unicode normalization, and == compares references.

Do not split a surrogate pair at a char index; substring throws IndexOutOfBoundsException for bad bounds, and one grapheme can contain several code points.

For A😀, length prints 3 UTF-16 units and codePointCount prints 2 code points; two new Strings produce false true for == and equals.

Examples

public class Main {
    public static void main(String[] args) {
        String text = "A😀";
        System.out.println(text.length());
        System.out.println(text.codePointCount(0, text.length()));
        String first = new String("java");
        String second = new String("java");
        System.out.println((first == second) + " " + first.equals(second));
    }
}

Result

3
2
false true

For A😀, length prints 3 UTF-16 units and codePointCount prints 2 code points; two new Strings produce false true for == and equals.

Sources