programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Operators

Ranch Hand
Posts: 56
• Number of slices to send:
Optional 'thank-you' note:
class EBH020 {
public static void main (String[] args) {
int a = 1 | 2 ^ 3 & 5;
int b = ((1 | 2) ^ 3) & 5;
int c = 1 | (2 ^ (3 & 5));
System.out.print(a + "," + b + "," + c);
}}

Please explain me the output of the above code.

Ranch Hand
Posts: 341
• Number of slices to send:
Optional 'thank-you' note:
int a = 1 | 2 ^ 3 & 5
= 0001 | 0010 ^ 0011 & 0101
-----------------------------------------
int b = ((1 | 2) ^ 3) & 5
= ((0001 | 0010) ^ 0011) & 0101
= (0011 ^ 0011) & 0101
= 0000 & 0101
= 0000
= 0
-----------------------------------------
int c = 1 | (2 ^ (3 & 5))
= 0001 | (0010 ^ (0011 & 0101))
= 0001 | (0010 ^ 0001)
= 0001 | 0011
= 0011
= 3
-----------------------------------------

Ranch Hand
Posts: 7729
• Number of slices to send:
Optional 'thank-you' note:
a gives the same result as c (3) because the expressions are really the same due to the relative binding strength of the operators &, ^, and |.

Ranch Hand
Posts: 52
• Number of slices to send:
Optional 'thank-you' note:
so, for a), the order of precedence is & , ^ and then |. Is that right?

Barry Gaunt
Ranch Hand
Posts: 7729
• Number of slices to send:
Optional 'thank-you' note:
Don't take my word for it, do what I did; find a precedence table:
Roedy Green's for example.
[ December 03, 2004: Message edited by: Barry Gaunt ]

Mathangi Shankar
Ranch Hand
Posts: 56
• Number of slices to send:
Optional 'thank-you' note:
Thanks All. I was struglling with the output of the 1st one then found that the order of precedence is |,^,& in the ascending order.

& has the highest order of precedence.

--------------------------------------------

Mathangi.

Greenhorn
Posts: 14
• Number of slices to send:
Optional 'thank-you' note:
A word of advice if you're going to take the SCJP exam.

MEMORIZE the precedence rules! Just like you have to know the keywords,
all 49 of them, know these rules too.
-Bruce

Originally posted by Mathangi Shankar:
class EBH020 {
public static void main (String[] args) {
int a = 1 | 2 ^ 3 & 5;
int b = ((1 | 2) ^ 3) & 5;
int c = 1 | (2 ^ (3 & 5));
System.out.print(a + "," + b + "," + c);
}}

Please explain me the output of the above code.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?