wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes shift operator question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "shift operator question" Watch "shift operator question" New topic
Author

shift operator question

Chitra Jay
Ranch Hand

Joined: May 02, 2002
Posts: 76
Given a variable x of type int(which may contain a negative value) which are correct ways of doubling the value of x,barring any overflow?
(a) x << 1;
(b) x <<= 1;
The answer is (b).
Can anybody please explain why?? i thought both are correct.
Thanks
geetha nagarajan
Ranch Hand

Joined: Jul 13, 2001
Posts: 94
a.)x << 1:The value is not assigned back to x,after shifting.
b.)x <<=1 :It's actually : x=x<<1.
So,after shifting,the value is assigned back to x.
Am i right?
Chitra Jay
Ranch Hand

Joined: May 02, 2002
Posts: 76
Can anybody please explain this with an example?
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Chitra Jay:
Can anybody please explain this with an example?

Just write a program, compile it, and execute it. That will tell you what happens. Try this:

What's the result? If you don't understand why you get the results that you get, please ask.
Corey


SCJP Tipline, etc.
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4445
    
    5

Don't know what else you're looking for. Would this help?

Junilu
Chitra Jay
Ranch Hand

Joined: May 02, 2002
Posts: 76
Oops!! Forgot the concept that the value of the left-hand operand is NOT affected by the shift operator ,whereas in the second case,x gets the new value due to extended assignment..Yeah I got it!! Thanks a lot for your examples..
 
 
subject: shift operator question
 
Similar Threads
question abt operator
Mughal Q3.14
int c=1; c=c++; // c is then 1 not 2 !
IllegalArgumentException
Mock Exam qs...