Search code examples
javaarraysforeachequalsarrayindexoutofboundsexception

ArrayIndexOutOfBound error when i used enhanced for loop


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...");
        }
    }
}


Solution

  • 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...");
        }
    }