This method is used to get the character at the specified index. The index number should be between the 0 to length-1. If length is not lies between 0 to length-1 it will throw StringIndexOutOfBoundsException. We will discuss it later.
The return type of charAt() is char. Where char is a data type used for characters.
stringName.chartAt(index)
stringName: The name of string in which you want to find the character.
index: Index will be the position of the character in a string. It should be an integer from 0 to length-1.
class ExampleOfCharAt
{
public static void main(String args[])
{
String name = "Ravi";
Char charAtPosition = name.charAt(3); //returns the char value at the 3th index
System.out.println("The character present at index 3 is = " +charAtPosition);
}
}
Output: The character present at index 3 is = i
StringIndexOutOfBoundsException with charAt(): The index should be an integer and it should be lies between the 0 to length-1. If you will try to with any illegal index value it will throw an exception.
class PerformanceExample
{
public static void main(String args[])
{
String name = "Ravi";
Char charAtPosition = name.charAt(5); //returns the char value at the 5th index
System.out.println("The character present at index 5 is = " +charAtPosition);
}
}
Output: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:693) at PerformanceExample.main(PerformanceExample.java:6)