0

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 '/'.?

Makoto
  • 104,088
  • 27
  • 192
  • 230
Raj
  • 1,945
  • 20
  • 40

1 Answers1

5

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

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • +1 precedence determines where the implied parenthesis are, not the order of evaluation (though it is rated). – Peter Lawrey Jun 22 '14 at 19:41
  • Thank you guys, I got confused with precedence and associativity and order of evaluation of subexpressions. After reading your comments I got the idea where I was going bonkers. Also delving more into the topic I found another stack overflow answer that explains it all in depth. Posting the link so that others may find it usefull http://stackoverflow.com/questions/6800590/what-are-the-rules-for-evaluation-order-in-java. Again thank you all for helping me – Raj Jun 23 '14 at 07:40