The charAt() method returns the character at the specified index.
Example
Syntax of charAt()
The syntax of the string charAt() method is:
string.charAt(int index)
Here, string is an object of the String class.
charAt() Parameters
- index - the index of the character (an
intvalue)
charAt() Return Value
- returns the character at the specified
index
Note: If the index passed to chartAt() is negative or out of bounds, it throws an exception.
Example: Java String charAt()
In Java, the index of Strings starts from 0, not 1. That's why chartAt(0) returns the first character. Similarly, charAt(5) and charAt(6) return the sixth and seventh character respectively.
If you need to find the index of the first occurrence of the specified character, use the Java String indexOf() method.