String charAt() Method in Java with Example

Why use string "charAt" Method?

The charat method returns the character at the definite index. In this method index value should be between 0 and string length minus 1

Method Syntax:

public char charAt(int index)

Parameter input:

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

Method Returns:

This method returns a character type data based on the index input

Exception:

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

Example 1:

public class CharAtgtupapers {
    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);
    }
}

Output:

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 this Java charAt method:

 

YOU MIGHT LIKE: