• 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 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

shiftoperators

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
anyone please explain the following program
The following code will print
1: int i = 1;
2: i <<= 31;<br /> 3: i >>= 31;
4: i >>= 1;
5:
6: int j = 1;
7: j <<= 31;<br /> 8: j >>= 31;
9:
10: System.out.println("i = " +i );
11: System.out.println("j = " +j);
A) i = 1
j = 1
B) i = -1
j = 1

C) i = 1
j = -1

D) i = -1
j = -1

answer
thanks in advance
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
chandana,
You name doesn't comply with our naming policy here at the Ranch. Take a look here for more info: www.javaranch.com/name.jsp
Please re-register with a more appropriate name.
Thanks
Bill
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Now to answer your question, the answer is D.
Take 1 and do a left shift 31 spaces and you get 100000000...
Now, do a signed right shift by 31 and you get 111111111....
Now do a signed right shift by 1 more and you get 11111111... still
Which leaves you with -1. Same for j but you don't do the last step, but since the last step doesn't do anything, it doesn't really matter.
Bill
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Answers : -1, -1.
After 1 is left shifted by 31, the high order bit is 1. When this is right shifted by 31, all the 32 bits are 1's. That is -1. In case of i which is again right shifted by 1, still all the bits are 1's. Thus the result.
Bala Arul.
 
You got style baby! More than this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic