Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

shift operator question  RSS feed

 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody please explain this with an example?
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Sheriff
Posts: 12747
210
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know what else you're looking for. Would this help?

Junilu
 
Chitra Jay
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..
 
I will open the floodgates of his own worst nightmare! All in a tiny ad:
Download Free Java APIs to Work with Office Files and PDF
htttp://www.e-iceblue.com/free-apis.html
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!