Skip to content

Latest commit

 

History

History
92 lines (76 loc) · 1.77 KB

for-and-enhanced-for-loop-internals.adoc

File metadata and controls

92 lines (76 loc) · 1.77 KB

Java for loop internals

Regular for loops

For statements are essentially compiled into equivalent while loops.

Original code
for (int i = 0; i < 5; ++i) {
    // ...
}
Compiled equivalent
int i = 0;
while (i < 5) {
    // ...
    ++i;
}

The for and while statements above both compile into the exact same bytecode.

Bytecode
 0: iconst_0
 1: istore_1
 2: iload_1
 3: iconst_5
 4: if_icmpge     13
    // ...
 7: iinc          1, 1
10: goto          2
13: return

Enhanced for loops (over arrays)

Enhanced for loops over arrays compile into while loops that are almost identical to that of regular for loops iterating over an entire array.

Original code
for (String value : arrayExpr) {
    // ...
}
Compiled equivalent
$array = arrayExpr;
$length = $array.length;
$i = 0;
while ($i < $length) {
    String value = $array[$i];
    // ...
    ++$i;
}

Note, that the result of the inital array expression needs to be stored in an unnamed variable, because the re-evaluation of the expression might not be side-effect free.

Enhanced for loops (over Iterables)

Enhanced for loops over iterables compile into a while loop equivalent using the iterable / iterator api.

Original code
for (String value : iterable) {
    // ...
}
Compiled equivalent
$iterator = iterable.iterator();       // 1
while ($iterator.hasNext()) {          // 2
    String value = $iterator.next();   // 3
    // ...
}
  1. The Iterator<T> object is retrived.

  2. The loop will continue as long as hasNext() returns true.

  3. The Iterator’s next() method is called to retrieve the current item and to advance the iterator.