Java Operator Priority

I am confused about what is true regarding operator precedence in Java. I have long read in textbooks that AND has a higher priority than OR, as evidenced by the answers presented in question . However, I am currently learning 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 copy and quote an explanation of how the compiler processes the above code:

If (x > 3) true , and either (y < 2) or the result of doStuff() is true , then type "true" . Due to the && short circuit, the expression is evaluated as if it had parentheses around (y < 2) | doStuff() (y < 2) | doStuff() . In other words, it evaluates to one expression before && and one expression after && .

This means that | has a higher priority than && . Is this due to the use of a “short circuit OR” and instead of a short circuit OR? Really?

+4
source share
2 answers

This is because instead of || operator is used | which has a higher priority. Here is a table .

Use the || operator instead and he will do what you think.

+8
source

Due to the short circuit & &, the expression is evaluated as if there were parentheses around (y <2) | doStuff () ...

This statement is false, really meaningless. The fact that && is a short-circuit operator has nothing to do with the estimate (y <2) | doStuff (), and indeed, this could be compiled if doStuff () returned a boolean. What is the difference (implicit parentheses) is the && priority over |, which is defined in JLS ## 15.22-23 as && below.

0
source

All Articles