wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Booleans and Operator precedence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Booleans and Operator precedence" Watch "Booleans and Operator precedence" New topic
Author

Booleans and Operator precedence

leo donahue
Ranch Hand

Joined: Apr 17, 2003
Posts: 327
How does this happen?
boolean b1 = true;
boolean b2 = false;
boolean b3 = false;
b3 &= b1 | b2; // prints false...
b3 = b3 & b1 | b2; // prints true...
Operator precedence is &, ^, |
so why does the grouping change???
Is it because of the &= assignment operator? This is weird, but neat.


Thanks, leo
leo donahue
Ranch Hand

Joined: Apr 17, 2003
Posts: 327
b2 should be true.
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10

The first println always prints false regardless of whether b1 and/or b2 are true or false because b3 is false. false & anything is false.
[ April 24, 2003: Message edited by: Marilyn de Queiroz ]

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Is it because of the &= assignment operator?
Yes. &= has the same precendence as =, which is much lower than the precedence for & or |. So,
b3 &= b1 | b2
evaluates as
b3 &= (b1 | b2)
while
b3 = b3 & b1 | b2
evaluates as
b3 = ((b3 & b1) | b2)


"I'm not back." - Bill Harding, Twister
leo donahue
Ranch Hand

Joined: Apr 17, 2003
Posts: 327
Thank you sheriffs.
I appreciate your help.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Things like this make good questions for tests, only because they have right and wrong answers and are easy to grade. I'd like to see choices in tests like:
A) This will print TRUE
B) This will print FALSE
C) Fire the programmer.
In practice, I never trust the compiler, my memory or my reader's memory, and always use parens to express my intent.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Booleans and Operator precedence
 
Similar Threads
Doubt on Self Test Question
conditional operator precedence
regarding preceedence
operator
Boolean operators