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

前端 未结 3 1599
星月不相逢
星月不相逢 2020-12-11 20:18
int it=9, at=9;

if(it>4 || ++at>10 && it>0)  
{
    System.out.print(\"stuff\");    
}

System.out.print(at);

prints out stuff9 a

3条回答
  •  半阙折子戏
    2020-12-11 21:07

    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.

提交回复
热议问题