Consider simple example
private static String isPositive(int val) {
if (val > 0) {
return "yes";
} else {
return "no";
}
}
Here it's pretty straightforward: if val > 0 return yes else return no.
But after compilation, in bytecode, this if condition is reversed:
private static isPositive(I)Ljava/lang/String;
L0
LINENUMBER 12 L0
ILOAD 0
IFLE L1
L2
LINENUMBER 13 L2
LDC "yes"
ARETURN
L1
LINENUMBER 15 L1
FRAME SAME
LDC "no"
ARETURN
It checks: if val <= 0 then return no, else return yes.
First, I thought that <= check is cheaper, and it's some kind of optimization. But if I change my initial code to
if (val <= 0) {
return "no";
} else {
return "yes";
}
it still will be reversed in bytecode:
L0
LINENUMBER 12 L0
ILOAD 0
IFGT L1
L2
LINENUMBER 13 L2
LDC "no"
ARETURN
L1
LINENUMBER 15 L1
FRAME SAME
LDC "yes"
ARETURN
So, is there a reason for such behavior? Can it be changed to straightforward?