Why does the “or” go before the “and”?

↘锁芯ラ 提交于 2019-11-28 13:51:45

Operator precedence only controls argument grouping; it has no effect on execution order. In almost all cases, the rules of Java say that statements are executed from left to right. The precedence of || and && causes the if control expression to be evaluated as

it>4 || (++at>10 && it>0)

but the higher precedence of && does not mean that the && gets evaluated first. Instead,

it>4

is evaluated, and since it's true, the short-circuit behavior of || means the right-hand side isn't evaluated at all.

Your compound expression is equivalent to

if(it>4 || (++at>10 && it>0))  

due to Java operator precedence rules. The operands of || are evaluated left to right, so it>4 is evaluated first, which is true, so the rest of it (the entire && subexpression) doesn't need to be evaluated at all (and so at does not change).

I feel I should add how to actually get your expected output.

Brief explanation: the || operator short-circuits the entire expression, thus the right side not even being evaluated.

But, to not short-circuit and get your expected output, instead of the || operator, just use |, like so:

int a = 9, b = 9;

if(a>4 | ++b>10 && a>0)  
{
    System.out.print("stuff");    
}
System.out.print(b);

The output to that is stuff10

This way, regardless of one side being true or not, they're both still evaluated.

The same thing goes for && and &

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!