Java String charAt() Method with Example

What is Java String charAt() Method?

The Java String charAt() method returns the character at the definite index from a string. In this Java method, the string index value starts from 0 and goes up to string length minus 1 (n-1).

charAt() Method Syntax

public char charAt(int index)

Parameter Input for charAt() Method

index – This Java method accepts only single input which is an int data type.

Return Type of Java String charAt() Method

The Java String charAt() method returns a character type data based on the index input.


Throws java.lang.StringIndexOutOfBoundsException if index value is not between 0 and String length minus one

Example of Java String charAt() Method

public class CharAtGuru99 {
    public static void main(String args[]) {
        String s1 = "This is String CharAt Method";
        //returns the char value at the 0 index
        System.out.println("Character at 0 position is: " + s1.charAt(0));
        //returns the char value at the 5th index
        System.out.println("Character at 5th position is: " + s1.charAt(5));
        //returns the char value at the 22nd index
        System.out.println("Character at 22nd position is: " + s1.charAt(22));
        //returns the char value at the 23th index
        char result = s1.charAt(-1);
        System.out.println("Character at 23th position is: " + result);


Character at 0 position is: T
Character at 5th position is: i
Character at 22nd position is: M

Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: -1

Some important things about the Java charAt() method:

  • This Java method takes an argument which is always int type.
  • This method returns the character as char for the given int argument. The int value specifies the index that starts at 0.
  • If the index value is higher than string length or a negative, then IndexOutOfBounds Exception error occurs.
  • The index range must be between 0 to string_length-1.