2

Since enhanced for loops are read only, it seems like each element is being copied into the new variable that you define when setting up the loop. Is there an implicit statement here? Maybe something like this:

int[] numbers = {1, 2, 3};
for(int number : numbers){
  numbers = numbers[i]; // Implicit statement?  Problem: the i variable does not exist.
  // Do stuff...
}
  • 1
    *Problem: the i variable does not exist.* It exists, the compiler named it and inserted it, and hides it from you. – Elliott Frisch Nov 30 '18 at 13:27
  • Java doesn't have references to primitives esp elements of an array or references to references. As such, there is no simple way to implement a modifiable variable which implicitly changes a value somewhere else. It can be done, but it would require a lot more syntactic sugar than you might imagine. – Peter Lawrey Nov 30 '18 at 13:28
  • 1
    Re @xtratic's proposed dupe target: If you dig through the answers long enough, you eventually find [this one](https://stackoverflow.com/a/33232565/157247), which is the most relevant to what you're asking. (That question is about looping through an `Iterable`, not an array, so most of the answers focus on the form of `for` that deals with `Iterable`s, which is different from the form dealing with arrays. That answer describes both.) – T.J. Crowder Nov 30 '18 at 13:31

1 Answers1

5

Yes, exactly, the enhanced for loop's processing creates a local variable within the block. Per JLS§14.4.2, for arrays, the enhanced for loop is equivalent to this:

The enhanced for statement is equivalent to a basic for statement of the form:

...

for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

(It's slightly different if the target of the loop is an Iterable instead of an array, but similar.)

Applying that to your loop:

int[] numbers = {1, 2, 3};
for (int i = 0; i < numbers.length; i++) {
  int number = numbers[i];
  // Do stuff...
}

The i variable (listed as #i in the spec) is not accessible to you, but it's there in the bytecode.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875