In Java, the charAt()
function returns a character at the specified index of a string.
The general syntax of the charAt()
function is as follows:
charAt(index)
The index is a parameter passed to the function which is an integer value, ranging from 0
to n-1
, where n
is the size of the string.
The charAt()
function returns a character value present at the specific index.
The following piece of code explains the functionality of the charAt()
function.
class HelloWorld {public static void main( String args[] ) {String str = "Hello!";char ch = str.charAt(4);System.out.println(ch);}}
In case the user gives an invalid input, that is, an index value less than 0
or greater than the size of the string, a string index out of bounds exception is thrown.
Execute the following code to see the exception:
class HelloWorld {public static void main( String args[] ) {String str = "Hello!";char ch = str.charAt(6);System.out.println(ch);}}