Reputation: 1965
My doubt is about the precedence of short circuit operators.
Classic example of short circuit operator is below.
if(denom != 0 && num/denom > 10 )
Here usage of shorthand operator allows us to prevent division by zero error because num/denom is never executed.
Now My question is Java says '/' operator has higher precedence than '&&' , then how come left side of '&&' is evaluated before '/'.?
Upvotes: 0
Views: 712
Reputation: 692231
/
has higher precedence than >
, which has a higher precedence than &&
. So, the expression
a && b / c > 0
is the same as
a && (b / c) > 0
which is the same as
a && ((b / c) > 0)
The expression is then evaluated from left to right.
If a
is false, then the entire expression is false, without even evaluating the second term.
If a
is true, then b / c
is first evaluated, and the result is compared to 0.
Upvotes: 5