ArrayIndexOutOfBound error when i used enhanced for loop

81 Views Asked by At

Can we use enhanced for loop without getting ArrayIndexOutOfBound error. because after using normal for loop it is working.

    public static void main(String[] args) {
        int a[] = {1,2,3,4};
        int b[] = {1,2,3,4};
 boolean status = true;
        if (a.length == b.length){
            for (int i:a){
                if (a[i] != b[i]){
                    status =false;
                }
            }
        }
        else {
            status = false;
        }

        if (status == true){
            System.out.println("arrays are equal...");
        }
        else {
            System.out.println("arrays not equal...");
        }
    }
}

2

There are 2 best solutions below

3
jmizv On BEST ANSWER

That is because you are accessing the elements of array a.

The loop

for (int i : a) {
  System.out.println(i);
}

will print out the values: 1, 2, 3, 4.

You probably expected to get 0, 1, 2, 3 but that is not how the enhanced loop work.

Improvement

Instead of comparing the two array by hand, you can use the convenience method Arrays.equals():

public static void main(String[] args) {
    int a[] = {1,2,3,4};
    int b[] = {1,2,3,4};
    boolean status = java.util.Arrays.equals(a, b);

    if (status){
        System.out.println("arrays are equal...");
    } else {
        System.out.println("arrays not equal...");
    }
}
0
Metin Bulak On

for (int i:a) // you mistake here, i equal to 1,2,3,4 array index must start 0

 public static void main(String[] args) {
        int a[] = {1,2,3,4};
        int b[] = {1,2,3,4};
 boolean status = true;
        if (a.length == b.length){
            for (int i=0; i<a.length; i++){  // look at here 
                if (a[i] != b[i]){
                    status =false;
                }
            }
        }
        else {
            status = false;
        }

        if (status == true){
            System.out.println("arrays are equal...");
        }
        else {
            System.out.println("arrays not equal...");
        }
    }
}