Initializing an array in Java using the ‘advanced’ for each loop [duplicate]

No, because you aren’t assigning to the array, you are assigning to the temporary variable called i. The array doesn’t see the change.

The following shows roughly equivalent code using the normal for loop. This should make it easier to see why it fails to update the array:

for (int j = 0; j < numbers.length; j++) { 
    Integer i = arr[j]; // i is null here.
    i = counter++; // Assigns to i. Does not assign to the array.
}

Leave a Comment