• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

complex boolean expressions without parentheses

 
Sigrid Kajdan
Ranch Hand
Posts: 72
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody please tell me how boolean expressions like

if (b1 & b2 | b3)
if (b1 | b2 & b3 & b4)

are evaluated (I mean, without parentheses to group the variables)?

Thanks
 
Henry Wong
author
Marshal
Pie
Posts: 20820
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Evaluation order is based on the operators precedence and the associatively. In this case, the AND operator has a slightly higher precedence than the OR operator. And they both have left-right assoc. So...

if (b1 & b2 | b3) ===> if ((b1 & b2) | b3)

if (b1 | b2 & b3 & b4) ===> if (b1 | ((b2 & b3) & b4))

Henry
 
victor kamat
Ranch Hand
Posts: 247
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The order of boolean operator precedence is

0 !
1&
2^
3|
4&&
5||

Hope that helps
 
Sigrid Kajdan
Ranch Hand
Posts: 72
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both very much! This was really help.
In fact, I somehow seemed to think that && and || had the same operator precedence...
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On the older versions of the exam, understanding these kinds of precedence rules was important. On the newer versions we've just added parentheses so that you won't have to memorize this stuff. If you encounter mock exam questions that test you on precedence, just know that that's an old style question and not too valid anymore.

hth,

Bert

p.s. That said, the short circuit operators are STILL important to understand
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic