The charAt(int index) method in Java is used to retrieve the character at a specific index in a string. It is a part of the String class in Java.
Syntax:
public char charAt(int index)
Parameters:
index: The index of the character you want to access. The index is 0-based, meaning the first character is at index 0, the second at index 1, and so on.
Return Value: The method returns the character at the specified index in the string.
Example:
public class CharAtExample {
public static void main(String[] args) {
String str = "Hello, World!";
// Retrieve the character at index 0 (first character)
char charAt0 = str.charAt(0);
System.out.println("Character at index 0: " + charAt0); // Output: H
// Retrieve the character at index 4 (5th character)
char charAt7 = str.charAt(7);
System.out.println("Character at index 7: " + charAt7); // Output: o
}
}
Handle StringIndexOutOfBoundsException
This exception is thrown if the index is negative or greater than or equal to the length of the string.
Example:
public class CharAtExceptionExample {
public static void main(String[] args) {
String str = "Hello, World!";
try {
char invalidChar = str.charAt(18);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage()); // Output: String index out of range: 18
}
}
Note: If you attempt to access an index that is out of the bounds of the string (such as str.charAt(18)), it will throw a StringIndexOutOfBoundsException.