What is String.charAt() in Java?

The String.charAt() method will return the character at the passed index.

Syntax

stringObj.charAt(int index);

This method will return a char value type.

Example

class CharAtExample {
public static void main( String args[] ) {
String str = "STRING";
char a;
System.out.println("The string is - " + str);
a = str.charAt(0);
System.out.println("\nstr.charAt(0) - " + a);
a = str.charAt(1);
System.out.println("str.charAt(1) - " + a);
a = str.charAt(2);
System.out.println("str.charAt(2) - " + a);
a = str.charAt(3);
System.out.println("str.charAt(3) - " + a);
a = str.charAt(4);
System.out.println("str.charAt(4) - " + a);
a = str.charAt(5);
System.out.println("str.charAt(5) - " + a);
}
}

In the code above, we created a string with the value STRING and got the character of the string using the charAt function. This function will return the character at the passed index.


If the passed index is less than 0 or greater than or equal to string length, then we will get StringIndexOutOfBoundsException. The index should be:

index >= 0 and index < string.length()

Free Resources