What javac does
Boolean logic and the ternary operator
No boolean instructions: && and || become chains of jumps.
The JVM has no boolean type and no instructions for && or ||. A boolean expression compiles to branches that end at code pushing 1 (iconst_1) or 0 (iconst_0).
The source
// && and || become chains of jumps; there are no boolean instructions.
public class Conditions {
static boolean inRange(int x, int lo, int hi) {
return x >= lo && x < hi;
}
static String sign(int x) {
return x > 0 ? "positive" : x < 0 ? "negative" : "zero";
}
static boolean either(boolean a, boolean b) {
return a || b;
}
}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
x >= lo && x < hi, each comparison is inverted and jumps to the false result; falling through both pushes 1. ||is the mirror image: the first test that succeeds jumps straight to the true result.- The nested ternary in
sign()becomes a chain of branches withgotos to a sharedareturn. - The branches test the opposite of the source (
ifleforx > 0) because javac jumps past the code for the true case.