1

I can't come up with an idea on why the array is printing out the int's in order instead of the order that they're put in the array.

int[] array = {1, 4, 0, 3, 2};
for(int i : array){
        System.out.println(array[i]);
}

Is there any explanation of this?

Thanks in advance!

  • the `i` does not represent the index, it´s rather a value returned by the `Iterator` and the current element of it – SomeJavaGuy Mar 09 '16 at 08:53

1 Answers1

4

You should be printing the loop's variable :

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

If you print array[i] instead of i, you get 4 instead of 1 as the first printed element, since array[1] == 4.

Your code would be correct if you were using the traditional for loop, which iterates over the indices of the array :

for(int i = 0; i < array.length; i++){
    System.out.println(array[i]);
}
Eran
  • 387,369
  • 54
  • 702
  • 768