Register Login

Java String charAt() method

Updated Nov 15, 2019

The Java String charAt() method returns the char value (character) at the specified index number. The index value should be between 0 and (string length-1); otherwise, the method will throw IndexOutOfBoundsException.  

For example, charAt(1) will return the second character of the string, and charAt(0) will return the first character of the string.

Syntax:

public char charAt(int index)  

Parameter

The Java String charAt() method only take one parameter i.e. index value.

Parameter Type Description
index (mandatory)  int specifies the position of the character to be returned by the method. 

Return Value

The Java String charAt() method returns the char value of the specified index.

Exception: 

The Java String charAt() method throws a StringIndexOutOfBoundsException exception if the index value is less than 0 (negative) or greater than the length of the string.

charAt() throws StringIndexOutOfBoundsException

//IndexOutOfBoundsException

//Main class of the program
public class Main {
    //Main method of the program
    public static void main (String[] args) {
        //String type variable
        String stechiesTitle = "STechies - Free Taraining Tutorials for Techie";
        //Variable to hold the number of counts of occurrence of character
        int count = 0;
        //For Loop of the iteration
        //For Loop will run equal to string length times + 1 times
        for(int i = 0; i < stechiesTitle.length()+1; i++){
            //storing the character in a temporary variable
            char x = stechiesTitle.charAt(i);
            //checking,Is character is equals to `s`
            if(x == 's'){
                //Increasing the count on each occurrence
                count++;
            }
        }
        //Printing the output
        System.out.println("s occurred "+count+" time in this string");
    }
} 

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8
    at java.lang.String.charAt(String.java:658)
    at Main.main(Main.java:10) 

 


×