Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Logical Operators Precedence

 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Ranchers

What is the precedence in below code ?



Any replies would be high appreciated.
 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another one :



This new one is evaluated as true and the last one is evaluated as false. Why ???
 
steven gerrard
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
| 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic