Hrishikesh Sardar
Hrishikesh Sardar

Reputation: 2917

What causes an ArrayIndexOutOfBoundsException?

    //Palindrone from a String
public class Palindrome {
    static int track = 0;
    public static void main(String args[]){
        String str = "abcicbbcdefggfed ";
        char[] charArray = str.toCharArray();
        Palindrome p1 = new Palindrome();
        p1.find_palindrome(charArray);
    }
    void find_palindrome(char[] ch){
        for(int i=0; i< ch.length; i++){
            if(ch[i] == ch[i+1]){
                checkPalindrome(ch, i, i+1);                
            }
            else{
                checkPalindrome(ch,i-1,i+1);
            }
        }       
    }
    void checkPalindrome(char[] c, int left, int right){
        int count=0,l=0,r=0;
        while(left >= 0 && right <= c.length){
            while(c[left] == c[right]){
                left--;
                right++;
                count = count + 1;
            }
            break;
        }
        if(count > track){
            track = count;
            l = left;
            r = right;
        }
        if(count>1){
            for (int j=left+1;j<=right-1;j++){
                System.out.println(c[j]);
            }       
            System.out.println("--");
        }       
    }
}

I am seeing the given exception error and I don't know how to solve. I know its beginner question, so an explanation along with your answer would really help.

Edit:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 17
    at Palindrome.find_palindrome(Palindrome.java:14)
    at Palindrome.main(Palindrome.java:8)

Upvotes: 0

Views: 585

Answers (2)

Maroun
Maroun

Reputation: 95958

Arrays are zero-based in Java (And most languages). This means, that if you have an array of size N, then the indexes are from 0 ... N - 1.

Your problem is here:

for(int i=0; i< ch.length; i++){
      if(ch[i] == ch[i+1]) 

What happens when i = ch.length - 1? What i + 1 will be?

Lets assume ch.length is 10, means that indexes are from 0 to 9, then ch.length - 1 is 9, but i + 1 is 10, which is out of bounds.

Upvotes: 3

Juned Ahsan
Juned Ahsan

Reputation: 68715

I think this statement is causing the exception:

        if(ch[i] == ch[i+1])

when you call it using the value of i just less than the length. This statement will cause the ArrayIndexOutOfBoundException. The first and last index of an array a is a[0] and a[a.length -1] respectively.

Upvotes: 1

Related Questions