aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Operators" Watch "Operators" New topic
Author

Operators

Mathangi Shankar
Ranch Hand

Joined: Nov 01, 2004
Posts: 56
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.


--------------------------------<br />SCJP1.4
Surasak Leenapongpanit
Ranch Hand

Joined: May 10, 2002
Posts: 341
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
-----------------------------------------
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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 |.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Sumithab Baskaran
Ranch Hand

Joined: Oct 29, 2004
Posts: 52
so, for a), the order of precedence is & , ^ and then |. Is that right?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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

Joined: Nov 01, 2004
Posts: 56
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.
Bruce Evans
Greenhorn

Joined: Nov 28, 2004
Posts: 14
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.
 
Consider Paul's rocket mass heater.
 
subject: Operators