Ambassador
Ambassador

Reputation: 33

Unable to find source of ArrayIndexOutOfBoundsException

I need some help to identify why this code is throwing an ArrayIndexOutOfBoundsException:

public class palindrome 
{
    public static void main(String[] args) 
    {
        String name = "Michael Knight";

        char ch[] = name.toCharArray();
        int size = name.length();

        for(int i = 0; i<size; i++) {
            //System.out.println(size);
            System.out.println(ch[i]);

            for(int j=size; j>=0; j--) {
                System.out.println(ch[j]);
            }
        }
    }
}

Upvotes: 0

Views: 72

Answers (4)

Jha
Jha

Reputation: 54

for(int j=size; j>=0; j--) {
            System.out.println(ch[j]);

j=size is out of bounds . The last index of array is size-1. j should be initialized with the last index of array in this case.

Upvotes: 0

Semih Eker
Semih Eker

Reputation: 2409

try like this;

public class palindrome{

   public static void main(String []arg$){

    String name = "Michael Knight";

    char ch[] = name.toCharArray();
    int size = name.length();

    for(int i = 0; i<size; i++){
        //System.out.println(size);
        System.out.println(ch[i]);

        for(int j=size-1; j>=0; j--){
            System.out.println(ch[j]);
        }

    }
  }
}

Upvotes: 0

Eran
Eran

Reputation: 393936

ch[j] is out of bounds when j==size, since the indices go from 0 to size-1.

It should be :

        for(int j=size-1; j>=0; j--){
            System.out.println(ch[j]);
        }

Upvotes: 4

Buhake Sindi
Buhake Sindi

Reputation: 89179

In the for loop, the j starts at index j=size which is already out of array bounds since the array starts from 0 to size - 1, thus ch[j] throws an ArrayIndexOutOfBoundsException.

The correct way to loop in reverse should be:

for(int j= (size - 1); j>=0; j--){
    System.out.println(ch[j]);
}

Upvotes: 1

Related Questions