In Java, charAt() returns the character at a zero-based index in a string. The first character is index 0.
You pass one index. It is required. The result is a char. An index outside the string throws StringIndexOutOfBoundsException.
Syntax
Call charAt on the string. Start with this line.
java
char c = text.charAt(0);
Call
What it does
text.charAt(0)
Returns the first character.
text.charAt(text.length() - 1)
Returns the last character.
Indexes use UTF-16 units. For emoji and other supplementary characters, prefer codePointAt.
Library declarations
java
public char charAt(int index);
Parameters
Parameter
Description
index
Required. The zero-based position of the character.
Return Value
Return Value
Description
char
The character at that index.
Java Examples
Example 1 — Read One Character
Fetch the character at index 7 in "Hello, Java!". Count from 0: space is at 6, so 'J' is at 7.
java
public class CharAtBasic {
public static void main(String[] args) {
String str = "Hello, Java!";
char result = str.charAt(7);
System.out.println("charAt(7) = " + result);
}
}
Output
charAt(7) = J
How It Works
Store the text.str holds "Hello, Java!" (12 characters).
Call charAt.str.charAt(7) reads the UTF-16 unit at index 7.
Get a char. Result is the primitive 'J', not a String.
Print it. Concatenation in println converts the char to text.
Example 2 — First and Last Character
Combine charAt() with length() to read both ends of a string.
java
public class FirstLastChar {
public static void main(String[] args) {
String word = "Java";
char first = word.charAt(0);
char last = word.charAt(word.length() - 1);
System.out.println("First: " + first);
System.out.println("Last: " + last);
}
}
Output
First: J
Last: a
How It Works
First index is always 0.charAt(0) → 'J'.
Find the last index.length() is 4, so last index is 4 - 1 = 3.
Read the end.charAt(3) → 'a'.
Avoid length() as an index.charAt(4) would throw—indexes stop at length() - 1.
Example 3 — Loop Through Every Character
Walk each index when you need both the position and the character— useful for parsing and validation.
java
public class CharAtLoop {
public static void main(String[] args) {
String text = "Hi";
for (int i = 0; i < text.length(); i++) {
System.out.println("Index " + i + ": " + text.charAt(i));
}
}
}
Output
Index 0: H
Index 1: i
How It Works
Start at 0. Loop variable i is the current index.
Stop before length. Condition i < text.length() keeps indexes valid.
Read each char.text.charAt(i) returns the character at that step.
Print index + value. You see both position and character—handy for debugging.
Frequently Asked Questions
charAt() returns the character at a zero-based index in a string.
index is required. It is the zero-based position.
A char at that index.
StringIndexOutOfBoundsException is thrown.
Prefer codePointAt() for full Unicode code points. charAt() works on UTF-16 units.