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?
That's because it is using the |
operator instead of ||
, which has a higher priority. Here's the table.
Use the ||
operator instead and it'll do what you think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With