What javac does
The enhanced for loop
An index loop over arrays, an Iterator over everything else.
The enhanced for loop compiles two different ways. Over an array it becomes an index loop, with hidden copies of the array reference and its length. Over anything Iterable it becomes calls to iterator(), hasNext() and next().
The source
// The enhanced for loop: an index loop over arrays, an Iterator over everything else.
import java.util.List;
public class ForEach {
static int sum(int[] values) {
int total = 0;
for (int v : values) {
total += v;
}
return total;
}
static int totalLength(List<String> words) {
int total = 0;
for (String w : words) {
total += w.length();
}
return total;
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
- In
sum(int[]), slots 2, 3 and 4 hold the copied array, its length and the index: local variables you never declared, which have no names in the LocalVariableTable. arraylengthis read once, before the loop, so assigning a different array to the variable inside the loop does not change what is iterated.- Over a
List<String>,next()returns Object, so javac addscheckcastString: generics are erased. - Both loops test at the top and jump back with
goto.