If this were an array of objects, it would still fail. Basically, for-each assigns each entry in the collection or array, in turn, to the variable you provide, which you can then work with. The variable is not equivalent to an array reference. It is just a variable.

For-each cannot be used to initialize any array or Collection, because it loops over the current contents of the array or Collection, giving you each value one at a time. The variable in a for-each is not a proxy for an array or Collection reference. The compiler does not replace your "i" (from "int i") with "array[index]".

Solution:2

i is just a copy of the int at that point in the array, not a reference to it. The for-each loop doesn't work in this case.

Solution:3

Use

java.util.Arrays.fill(array, 24)

if you're going to be initializing to the same value. Other than that, Eddie is pretty much spot on in his translation of the for-each construct.

Solution:4

the int is a primitive type in the system, so you're actually getting a copy of the value of the cell in the array, rather than a reference to that cell in the array that you can assign into....

Let me try and explain this. If you had an array of Xs, where X is a class that has data members, you would be getting a reference to a different cell in each iteration, and would be able to change its state by calling functions on it (e.g., setValue).

When you have ints it's a different story, your int is not a reference, it is an actual value on the stack since it's a primitive type, so in each iteration, the for copies a value from the array into the i. You then update your i, but that has no effect on the array.