Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The precedence of java boolean

Tags:

java

boolean

&& is supposed to have higher precedence than ||:

    int a = 10;
    System.out.println(a==10 || --a==9 && a==8);
    System.out.println(a);

this prints true, and 10. It seems that it checks only the first part and if its true the second never executes.

If I do a==9 then the second part seems to evaluate and prints 9. Can someone explain why this is happening? Isn't && supposed to evaluate first?

Edit: I see it. a==10 || --a==9 && a==8 transforms into (a==10) || (a==9 && a==8) So if the first one evaluates to true it short circuits. Thank you for your help guys.

like image 867
xyclops Avatar asked Dec 15 '22 20:12

xyclops


2 Answers

System.out.println(a==10 ||  --a==9 && a==8);

equal to

System.out.println((a==10) ||  (((--a)==9) && (a==8)));

Java evaluates || first. Find out that left part (a==10) is true and derive that no mater what is in right part result anyway will be true

PS: it is common trick to write

if(obj != null && obj.isSomething) { ... }

to prevent NPE

like image 139
talex Avatar answered Dec 17 '22 09:12

talex


It's useful to look at expressions as trees.

a==10 ||  --a==9 && a==8

In this example, the top of the tree is an OR. The left branch is an EQUALS, and the right branch is an AND whose left and right branch are both EQUALS.

Since I'm awful at graphics, it would look something like:

    OR
   /   \-----
  =          \
 / \         AND
a  10       /   \
           =     =
          / \   / \
       --a   9 a   8

The "precedence" that you're talking about, orders this tree. But it doesn't necessarily change execution order. Because in this case, this is true if the first branch is true, so no need to check the second branch.

like image 32
Cruncher Avatar answered Dec 17 '22 11:12

Cruncher