This is my first post here so please forgive any protocol errors.
My question is simply trying to understand what is happening with the following Java code. I fully understand that the use of parentheses would clarify everything, but the resulting output seems to fly in the face of convention regarding Java order of operations.
public class Tester
{
public static void main(String[] args)
{
int total=9, num=13;
if (total>4 || ++num>15 && total>0)
{
System.out.println("short");
}
System.out.println(num);
}
}
The output is:
short
13
It is obvious the ++num did not execute. If strict order of operations had been observed it should have been the first thing to happen. It didn’t. So next is the &&. If the && is done by order of precedence over the ||, then the same…the ++num should happen first. It didn’t. So, to me it seems the output was determined with the || executed first, shortciruiting the ++num and then, working with the &&, resulted in the short being printed. Were the order of operation rules simply ignored and the Boolean expression executed left to right? Is the increment operator causing the irregular behavior?
Thanks for any insight as to what is actually going on with this code.
This has nothing to do with precedence/associativity (which deals with how expressions are parsed)… this has to do with Java evaluation order — which is left to right. You appear to be misunderstanding how short-circuit logic works.
Now, let’s attempt to evaluate this expression incrementally…
Since
total > 4evaluates totrue, the condition evaluates totrueand theifbranch is taken immediately rather than evaluating the rest of the conditional.If you change
totalto equal4, then the left-operand (total > 4) of the short-circuit OR isfalseand thus it evaluates the right-operand (++num > 15 && total > 0).If you change
numto equal15, then the short-circuit AND left-operand (++num > 15) evaluates totrueand thus it finally evaluates the AND right-operand (total > 0) to determine whether the conditional istrue. Iftotal > 0is false, then the conditional is alsofalse.Below is the code rewritten for clarity to highlight the flow.
You can read more on Java conditional operators in the relevant Java Tutorial.