Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java operators precedence

Tags:

java

operators

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) is true, and either (y < 2) or the result of doStuff() is true, 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?

like image 353
arjacsoh Avatar asked Feb 19 '23 01:02

arjacsoh


1 Answers

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.

like image 124
mprivat Avatar answered Mar 03 '23 03:03

mprivat