• Post Reply Bookmark Topic Watch Topic
  • New Topic

Operator Precedence???  RSS feed

 
ced ron
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm sorry if there's already similar question being posted. Can't seem to find it here.
Can someone help me with the following expression? Thanks!
Assuming b1, b2, b3 are boolean: ( b1 & b2 | b2 & b3 | b2)
Do we evaluate from
left to right or vice versa?
right to left or vice versa?
& operator then | operator or vice versa?
or some other way?
Does it matter if there's a combination of bitwise and logical operator? Will it affect the order of precedence?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37469
539
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The AND and OR operators are evaluated from left to right. All the ANDs are done before all the OR's. So your expression would be executed in the following order:
b1 & b2
b2 & b3
(b1 & b2) | (b2 & b3)
(b1 & b2) | (b2 & b3) | b2
If you are combining bitwise and logical operators, all the bitwise are evaluated first.
Sun has a chart on this and all the other operators.
 
ced ron
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help!
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch, ced ric!
Another good source for such language details is the Java Language Specification, which is available on-line at http://java.sun.com/docs/books/jls.
From the table of contents, notice that section 15 covers this topic.
[ October 12, 2003: Message edited by: Dirk Schreckmann ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps it would be appropriate here to say that, although there are clear rules for operator precedence, it is generally good practice to be explicit, by using parentheses (round brackets). Or, at least, I think so.
It is kinder to maintenance programmers who may have to deal with your code after you write it.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!