简体   繁体   中英

Java operators priority

I'm looking into the following part of code:

int a =2;
int b =3;
int c =4;
int d =4;
System.out.println(a==2 || (b==3&&c==4) && d==5);
System.out.println(d==5 && (b==3&&c==4) || a==2);

According to http://bmanolov.free.fr/javaoperators.php I expect && perform earlier then ||, so logically it should look like that

if(d==5&&((b==3&&c==4)||a==2)) 
if((a==2||(b==3&&c==4))&&d==5) 

and be false, but I'm getting true in both cases above.

What am I missing?


UPDATE: Please do not suggest results of true/true:

d==5&&((b==3&&c==4)||a==2) returns false

d==5&&(b==3&&c==4)||a==2 returns true

My question is that according to operators priority I believe

d==5&&(b==3&&c==4)||a==2 should be interpreted as

d==5&&((b==3&&c==4)||a==2)

According to the reference you give , && "binds tighter" than || (as it has a higher precedence), so a && b || c a && b || c is interpreted as (a && b) || c (a && b) || c and a || b && c a || b && c as a || (b && c) a || (b && c) . Thus, in all cases you have a==2 making everything true .

Especially, your belief expressed in

My question is that according to operators priority I believe

d==5&&(b==3&&c==4)||a==2 should be interpreted as

d==5&&((b==3&&c==4)||a==2)

is wrong.

In this part:

if(a==2||(b==3&&c==4)&&d==5){

It will evaluate a==2 and will say yes a is 2 so will print true irrespective of what's on the right hand side.

In other case:

if(d==5&&((b==3&&c==4)||a==2)) 

It will evaluate d==5 which is false and then straight away will see there is an or condition (will skip && condition) and will see a is 2 and will enter if and will print true.

In short, || and && is know as short circuit operation which evaluates all or none. Meaning if you have condition1 || condition2 condition1 || condition2 it will evaluate condition2 if and only if condition1 fails.

While if you have condition1 && condition2 , it will evaluate condition2 if and only if condition1 is true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM