How does primitive array work with new for each loop in Java?

I understand that new for each loop works with Iterable and arrays, but I don't know what goes behind the scenes when working with arrays.

Can anyone help me understand this? Thanks in advance.

int[] number = new int[10];

for(int i: number) {

}

The loop is equivalent to:

for(int j = 0; j < number.length; j++) {
  int i = number[j];
  ...
}

where j is an internally generated reference that does not conflict with normal user identifiers.


A bit late, but here it is.

The compiler knows if you are using the for-each loop statement for a collection or for an array.

If used for collection, the compiler translates the for-each loop to the equivalent for loop using an Iterator.

If used for an array, the compiler translates the for-each loop to the equivalent for loop using an index variable.

Here is a description at oracle.com


In your code, you allocate an array of 10 integers in the memory and obtain a reference to it. In the for-loop you simply iterate over every item in the array, which initially will be 0 for all the items. The value of every item will be stored in the variable i declared in your for-loop as you iterate the array elements.


this is equivalent to:

for(int x = 0; x < number.length; x++) {
  int i = number[x];
}