File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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)?

Henry Wong

Joined: Sep 28, 2004
Posts: 20521

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))


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 !

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

Joined: Oct 14, 2002
Posts: 8898
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.



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:
subject: complex boolean expressions without parentheses
It's not a secret anymore!