Reputation: 9232
I have got confused due to what is true regarding the operator precedence in Java. I read in tutorials a long time ago that AND has a higher priority than OR, which is confirmed by the answers provided in the question. However, I am currently studying Java using the "Sun Certified Programmer for Java 6 Study Guide". This book contains the following example:
int y = 5;
int x = 2;
if ((x > 3) && (y < 2) | doStuff()) {
System.out.println("true");
}
I am copying and citing the explanation of how the compiler handles the above code:
If (x > 3)
istrue
, and either(y < 2)
or the result ofdoStuff()
istrue
, then print"true"
. Because of the short-circuit&&
, the expression is evaluated as though there were parentheses around(y < 2) | doStuff()
. In other words, it is evaluated as a single expression before the&&
and a single expression after the&&
.
This implies though that |
has higher precedence than &&
. Is it that due to the use of the "non-short-circuit OR" and instead of the short circuit OR? What is true?
Upvotes: 4
Views: 1928
Reputation: 310909
Because of the short-circuit &&, the expression is evaluated as though there were parentheses around (y < 2) | doStuff() ...
This statement is incorrect, indeed meaningless. The fact that && is a short-circuit operator has nothing to do with the evaluation of (y < 2) | doStuff(), and indeed that could only compile if doStuff() returned a Boolean. What makes the difference (the implicit parentheses) is the precedence of && relative to |, which is defined in JLS ##15.22-23 as && being lower.
Upvotes: 0