-3

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 Answers2

1

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...");
    }
}
jmizv
  • 1,172
  • 2
  • 11
  • 28
  • 1
    I think you should suggest how to actually compare arrays manually, too. People in the LEARNING phase should FIRST code the solution themselves, and then you tell them: and in the real world, use this library call. – GhostCat Nov 25 '21 at 10:09
  • if (a.length == b.length){ for (int i:a){ if (a[i-1] != b[i-1]){ status =false; } } } now it is working – Prajakta Yadav Nov 25 '21 at 11:08
  • @Prajakta Yadav, this is only working because your array has these values: 1,2,3,4. Try with arrays like `{1,2,3,5}` or `{1,2,4}` and it won't work anymore. – jmizv Nov 25 '21 at 11:13
1

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



Metin Bulak
  • 537
  • 4
  • 8
  • 30