Java charat example – Java String Class charAt() Method with Example | How to Use String charAt() in Java?

Java charat example: The charAt() method of the String class is used to return the char value at the specified index. An index ranges from 0 to length() – 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the specified index is not there then you will get StringIndexOutOfBoundExceptions: string index out of range.

Syntax: The syntax of the String class charAt() method is given below.

public char charAt(int index)

Parameter:

index- Index of the character to be returned.

Here, the index is the index of the character that you want to obtain.

Return:

Charat() java: The charAt() method returns the character at the specified position.

Exception:

StringIndexOutOfBoundsException - You will get this exception if the index is negative or greater than the length of the string.

Also, See:

Java String charAt() Method Example

How to use charat in java: Let’s understand the String charAt() method with an example.

class charAtExample{
public static void main(String args[]){
String str = "Javastudypoint";
char ch = str.charAt(7); //returns the char value at 7th index.
System.out.println("The value at 7th index is: " +ch);
}
}

Output:

The value at the 7th index is: d

StringIndexOutOfBoundsException with charAt() Method

The charAt() method of the String class throws StringIndexOutOfBoundsException if the specified index argument is negative or the greater of the length of the string. Let’s see the example.

Case 1: When the index argument is greater than the length of the string.

class charAtExample{
public static void main(String args[]){
String str = "Javastudypoint";
char ch = str.charAt(20); //StringIndexOutOfBoundsException
System.out.println("The value at 7th index is: " +ch);
}
}

Output:

Java String Class charAt() Method with Example 1

Case 2: When the index argument is negative. Let’s see the example.

class charAtExample{
public static void main(String args[]){
String str = "Javastudypoint";
char ch = str.charAt(-10); //StringIndexOutOfBoundsException
System.out.println("The value at -10th index is: " +ch);
}
}

Output:

Java String Class charAt() Method with Example 2

Key Points to Remember regarding Java charAt() Method

  • It takes an argument that is always int type
  • Java MethodCharAt() returns the Character as Char for the int argument given. Int value specifies the index starting at 0.
  • If the index value of the string is negative or higher than the string length then the IndexOutOfBounds Exception occurs.
  • Index Range needs to be between 0 to string_length-1.