This week's book giveaway is in the Design forum.We're giving away four copies of Building Microservices and have Sam Newman on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Building Microservices this week in the Design forum!

# Operators

kapil munjal
Ranch Hand

Joined: May 11, 2004
Posts: 298

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.

This is a question from Dan's site.

Thanks
Kaps

(Corrected [C0DE][/C0DE] bracketing)
[ August 01, 2004: Message edited by: Barry Gaunt ]

Kapil Munjal
SCJP 1.4, SCWCD 1.4
Vikram Bindal
Greenhorn

Joined: Jul 30, 2004
Posts: 7
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

Joined: Apr 20, 2000
Posts: 3252
[...] 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 * / %
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

Joined: May 11, 2004
Posts: 298

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

I agree. Here's the link: http://aspose.com/file-tools

subject: Operators