Library contents

Java String.charAt

Read the UTF-16 unit at a zero-based position.

A simple example

String.charAt

  1. Start with "abc"
  2. Do this Read the second character
  3. Result "b"
Walk past a to reach b. These ASCII characters each occupy one byte in UTF-8.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("abc".charAt(1));
    }
}
Output
b

Syntax

Java 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.java

Read 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
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String pass = "B-204";
        System.out.println(pass.charAt(0));
    }
}
Output
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
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String code = "PK-482";
        System.out.println(code.charAt(code.length() - 1));
    }
}
Output
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.

Documentation for String.charAt