Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the "or" go before the "and"?

int it=9, at=9;

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

System.out.print(at);

prints out stuff9 and I want to know why as I thought ++at>10 && it>0 would be evaluated first and thus make at = 10.

like image 909
user3630501 Avatar asked Nov 29 '22 15:11

user3630501


2 Answers

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.

like image 187
user2357112 supports Monica Avatar answered Dec 11 '22 03:12

user2357112 supports Monica


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).

like image 45
Greg Hewgill Avatar answered Dec 11 '22 04:12

Greg Hewgill