# Logical Operators Precedence

Edisandro Bessa
Ranch Hand
Posts: 584
Dear Ranchers

What is the precedence in below code ?

Any replies would be high appreciated.

Edisandro Bessa
Ranch Hand
Posts: 584
Another one :

This new one is evaluated as true and the last one is evaluated as false. Why ???

steven gerrard
Ranch Hand
Posts: 55
| operator has higher precedence compared to && so in the forst case && is the last one to be executed and since b1 is false answer will be false irrespective of wat comes on the rhs of && .

in the second case precedence of & is more than | . so b1&b2 is evaluated first . this gives false then new expression becomes::
false|b2 & b3 | b4
now since & has higher prcedence over | b2&b3 is evaluated . this gives true

so now expression becomes ::
false|true|b4

now since binary operators are left associative false|true is evaluated . this gives true
so final exppression to be evaluated is ::
true|b4
which gives true

Seema Ahuja
Ranch Hand
Posts: 32
I am sorry i know this is a rather old topic but

if(b1 & b2 | b2 & b3 | b4)
System.out.println("Crazy stuff");

gives a compile time error. says operator & cannot be applied to Boolean and boolean

I created b1 as

Boolean b1 = new Boolean(false);
as it does not allow me to create a Boolean object like this:

Boolean b1= false;

Will anyone plz clarify

Thanks

Craig Tyler
Ranch Hand
Posts: 52
Originally posted by Seema Ahuja:
I am sorry i know this is a rather old topic but

if(b1 & b2 | b2 & b3 | b4)
System.out.println("Crazy stuff");

gives a compile time error. says operator & cannot be applied to Boolean and boolean

I created b1 as

Boolean b1 = new Boolean(false);
as it does not allow me to create a Boolean object like this:

Boolean b1= false;

Will anyone plz clarify

Thanks

It doesn't work if you are using java 1.4 or below. With java 1.5, the autoboxing and unboxing allows a boolean value to be directly assigned to a Boolean and for Boolean objects to be used with the & and | operators.

Edisandro Bessa
Ranch Hand
Posts: 584
Hi,

Just in addition to previous posts, after reading Steven's post I could realize that the precedence for logical operators are :

^ 1st --> & 2nd --> | 3rd --> && 4th --> || 5th.

Thank U Steven.