Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operators

 
kapil munjal
Ranch Hand
Posts: 298
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Hi,

Please explain how to evaluate the value of variable a.

I am able to understand the evaluation of variable b and c but a is still confusing for me.

Please help.

This is a question from Dan's site.

Thanks
Kaps

(Corrected [C0DE][/C0DE] bracketing)
[ August 01, 2004: Message edited by: Barry Gaunt ]
 
Vikram Bindal
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Regd the code evaluation for a
I struggled at first as well.. so I tried it out on the compiler and I saw the output 3, 0, 3
After trying different bracket combinations, it looks like this is what
the expression a is really like

int a = 1 | (2 ^ (3 & 5));

So 3 (0011) & 5 (0101) = 1 (0001), followed by
2 (0010) ^ 1 (0001) = 3 (0011), followed by
1 (0001) | 3 (0011) = 3 (0011)

I just wanted to consult an advice, are we expected to remember the order or preecedence for the exam, which in this case looks like & then ^ then |.

Can someone suggest !!.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vikramaditya Bindal:
[...] are we expected to remember the order or preecedence for the exam [...]
Yes. Briefly, operator precedence is

1 all unary operators ++ -- + - ~ ! (cast)
2 multiplication etc * / %
3 addition etc + -
4 shifting << >> >>>
5 comparison < <= > >= instanceof
6 equality == !=
7 and &
8 xor ^
9 or |
10 shortcircuiting and &&
11 shortcircuiting or ||
12 ternary operator ? :
13 assignment = *= /= %= += -= <<= >>= >>>= &= ^= |=

- Peter
[ July 31, 2004: Message edited by: Peter den Haan ]
 
kapil munjal
Ranch Hand
Posts: 298
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your replies...Vikramaditya and Peter.

Actually dan has given this explanation for this answer.

"Java evaluates operands from left to right while respecting operator precedence. The order of operator precedence starting with the lowest is as follows: |, ^, &. Although complete memorization of the operator precedence chart is not necessary, it is a good idea to memorize the three levels that appear in this question."

And he has written the "lowest" word, which was a little confusing and I could not understand how to reach this answer.

Thanks a lot for your replies...it really helps

Kaps
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic