String.charAt()
Returns the character at the given index.
Available since: Java 1.0
Syntax
public char charAt(int index)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | int | The position of the character, counting from zero. Must be from 0 to length() - 1. |
Return value
charThe character as a char value.
Examples
The first and the last character:
void main() {
String name = "Anna";
IO.println(name.charAt(0));
IO.println(name.charAt(name.length() - 1));
}Output:
A
aLooping over the characters:
void main() {
String word = "code";
for (int i = 0; i < word.length(); i++) {
IO.print(word.charAt(i) + " ");
}
IO.println();
}Output:
c o d e An index outside the string throws an exception:
void main() {
try {
"abc".charAt(3);
} catch (StringIndexOutOfBoundsException e) {
IO.println(e.getMessage());
}
}Output:
Index 3 out of bounds for length 3Notes
A char is a number, so 'a' + 1 gives 98, not "b". To join characters into a string, start the expression with a string: "" + c1 + c2.
See also
- String.length() — Returns the number of characters in a string.
- String.substring() — Returns the part of a string between two indexes.
- String.chars() — Returns a stream of the character codes of a string.
- String.indexOf() — Finds the position of the first occurrence of a character or a substring.
Related recipes
In the tutorial
- Strings — The String type in Java: creating strings, joining with +, length, characters by index, escaping and comparing with equals.