Search code examples
javaindexoutofboundsexception

find highest continuous occurence of a character in a string throws string index out of bounds


I am trying to do a program that finds the biggest continuous occurrence in a string. Here is my code.

public class Assign2{
    public int maxOcc(String str){
        System.out.println("Entered method");
        int j,i,counter;
        j  = i = 0;
        int max = 0;
        int size = str.length();
        System.out.println("Size of string-->"+size);
        for(i = 0;i<size;i++){
            j = i;
            counter = 0;
            while(str.charAt(i)==str.charAt(j) && j < size){
                counter++;
                j++;
            }
            if(counter > max)
                max = counter;
        }
        return max;
    }
    public static void main(String args[]){
        Assign2 a = new Assign2();
        System.out.println(a.maxOcc("abbbbaaaaaagsgsgaaaa"));
    }
}

However When I try to run this program I gen an"String index out of bounds".Any Ideas?


Solution

  • The problem is in this condition:

    while(str.charAt(i)==str.charAt(j) && j < size){
    

    Java evaluates left-to-right, so it evaluates str.charAt(j) before it checks j < size - so if j is too big (because you incremented in the loop), you will get an AIOOBE.

    Reverse the subexpressions:

    while (j < size && str.charAt(i)==str.charAt(j)){
    

    This doesn't fail because && short-circuits: once j < size is false, it doesn't bother checking the rest of it.