In this tutorial, you will learn about String charAt() method, its syntax, and usage with examples.

Java String charAt() method

In Java, String charAt() method takes an index (integer) value as argument, and returns the character in the string at the specified index.

Syntax of charAt()

The syntax to call String charAt() method in Java is

string.charAt(index)

charAt() has a single parameter.

ParameterDescription
index[Mandatory]An integer value.Specifies the index of the character to be returned.

charAt() returns value of char type.

charAt() throws IndexOutOfBoundsException if the given index is out of bounds for the characters in the given string.

ADVERTISEMENT

Examples

1. charAt(index) – Index within bounds of the string

In this example, we take a string value in str of length 10, and get the character at index=6, using String charAt() method.

Java Program

public class Main {
	public static void main(String[] args) {
		String str = "HelloWorld";
		char ch = str.charAt(5);
		System.out.println("Char at index=5 is : " + ch);
	}
}

Output

Char at index=5 is : W

2. charAt(index) – Index out of bounds for the string

In this example, we take a string value in str of length 10, and get the character at index=16, using String charAt() method.

Java Program

public class Main {
	public static void main(String[] args) {
		String str = "HelloWorld";
		char ch = str.charAt(16);
		System.out.println("Char at index=16 is : " + ch);
	}
}

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 16
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
	at java.base/java.lang.String.charAt(String.java:712)
	at Main.main(Main.java:4)

Conclusion

In this Java String Methods tutorial, we have seen about String charAt() method in Java, its syntax, and how to use String charAt() method in Java programs with the help of examples.