charAt() - String Method in Java


This article is a part of String Methods in Java.
charAt() returns the character at the specified index in a String. The parameter is of int type, representing the index of the character to return.


Return type

The return type for the charAt() method is char. Let us look at an example code to understand it better.

Example


Output

Let us look at the output of the above example code.

String Methods charAt()
Fig.1- String Methods : charAt()

IndexOutOfBound exception in charAt()

When we pass negative index or an index greater than length()-1 then the charAt() method throws IndexOutOfBound exception. Let us look at the code for this case.


Output

Let us look at the output of the above example code.

String Methods charAt() IndexOutOfBound
Fig.2- String Methods : charAt() IndexOutOfBound

Since, the index is a negative number the method throws an exception.

Read More

Author : Satyam Kumar -



You will also like: