CKTIS / Java
String.charAt — reading a UTF-16 code unit
String.charAt(int index) returns the char at a zero-based index. It reads a UTF-16 code unit, not necessarily a complete Unicode character.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public char charAt(int index)String.charAt(int index) returns a char, a UTF-16 code unit. A valid index satisfies 0 <= index && index < text.length(). The first unit has index 0.
A negative index or one equal to or greater than length() causes IndexOutOfBoundsException. An empty string has no valid index.
A character outside the BMP occupies a surrogate pair. charAt returns only one unit of that pair. In the example, text.charAt(1) is the high surrogate; text.codePointAt(1) reads the complete code point. Both methods use UTF-16 code-unit indices.
Examples
public class Main {
public static void main(String[] args) {
String text = "A\uD83D\uDE00B";
System.out.println(text.charAt(0));
System.out.println(text.length());
System.out.println((int) text.charAt(1));
System.out.println(text.codePointAt(1));
}
}Result
A 4 55357 128512
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.