What javac does
for, while and do-while
The test at the top and a goto at the bottom, except for do-while.
javac compiles for and while loops with the test at the top: a conditional jump out of the loop, the body, and a goto back to the test. A do-while has its test at the bottom and needs no goto.
The source
// for, while and do-while: the condition at the top, a backward goto at the bottom.
public class Loops {
static int forLoop(int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += i;
}
return sum;
}
static int whileLoop(int n) {
int steps = 0;
while (n != 1) {
n = n % 2 == 0 ? n / 2 : 3 * n + 1;
steps++;
}
return steps;
}
static int doWhile(int n) {
int digits = 0;
do {
n /= 10;
digits++;
} while (n != 0);
return digits;
}
}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
forLoop,if_icmpgeleaves the loop andi++is a singleiinc. while (n != 1)leaves withif_icmpeq, the opposite of the source condition.doWhilejumps back withifnewhile the condition holds: the only loop here whose branch says what the source says.- Backward branches are what the JVM counts to decide that a loop is hot enough to compile to machine code.
Loops.class
static int forLoop(int n)
javac --release 8 to 25 (the same bytecode for every release)