aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes complex boolean expressions without parentheses Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "complex boolean expressions without parentheses" Watch "complex boolean expressions without parentheses" New topic
Author

complex boolean expressions without parentheses

Sigrid Kajdan
Ranch Hand

Joined: Jan 14, 2007
Posts: 72
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
Sheriff

Joined: Sep 28, 2004
Posts: 19064
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
The order of boolean operator precedence is

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

Hope that helps
Sigrid Kajdan
Ranch Hand

Joined: Jan 14, 2007
Posts: 72
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

Joined: Oct 14, 2002
Posts: 8883
    
    5
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


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: complex boolean expressions without parentheses