Java String Class charAt() Method with Example

The charAt() method of 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) 
Here, the index is the index of the character that you want to obtain. The charAt() method returns the character at the specified position.


Java String Class charAt() method Example.

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 7th index is: d 


StringIndexOutOfBoundsException with charAt() Method.

The charAt() method of 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





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

Java String Class charAt() Method with Example Java String Class charAt() Method with Example Reviewed by Prashant Srivastava on January 03, 2020 Rating: 5

No comments:

Powered by Blogger.