How to get a character from a string in Java

In Java, the charAt() function returns a character at the specified index of a string.

svg viewer

Syntax

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.

Example

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);
}
}

Exception handling

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);
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved