Search code examples
javastringindexoutofbounds

StringIndexOutOfBoundsException when trying to count 'a's in the entered word in Java


public class methods {
    public static int howMany(String word) {
        char character = 'a';
        int a = 0;
        for (int i=0;i<=word.length();i++) {
            if (word.charAt(i)==character) {
                a++;
            }
        }
        return a;
    }
    public static void main(String[] args) {
        System.out.println(howMany("afdfaf"));
    }
}

code gives error. please help. I couldn't find where is the error.

Expected output:

2

Observed error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6

The exception happens in this line:

    if (word.charAt(i)==character) {

Solution

  • Change this line, you are exceeding the word length

    Rewrite:

    for (int i=0;i<=word.length();i++)
    

    into

    for (int i=0;i<word.length();i++)