Java String.charAt
Read the UTF-16 unit at a zero-based position.
A simple example
String.charAt
- Start with "abc"
- Do this Read the second character
- Result "b"
class Main {
public static void main(String[] args) throws Exception {
System.out.println("abc".charAt(1));
}
}
b
Syntax
public char charAt(int index)
JDK 21 method signatures (1)
public char charAt(int index)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead the zone on a boarding pass
A compact printed code assigns meaning to particular positions. Locate the correct character for the requested field and check the indexing convention before sending the value to the display.
From the programString pass = "B-204"
ResultB
class Main {
public static void main(String[] args) throws Exception {
String pass = "B-204";
System.out.println(pass.charAt(0));
}
}
B
The first unit identifies zone B.
Advertisements
Read a parcel check digit
A parcel scanner uses a single position for its check digit. Read that position from a sample code before using the digit to verify the rest of the scan.
From the programString code = "PK-482"
Result2
class Main {
public static void main(String[] args) throws Exception {
String code = "PK-482";
System.out.println(code.charAt(code.length() - 1));
}
}
2
The last valid index is one less than the length.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Read the first character to identify the routing area.
GivenNC-17
Worked resultN
What to watch for
An out-of-range index raises an exception. Use codePointAt when a symbol may require a surrogate pair.