• 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
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

about >>> question

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which of the following results in a negative value of a?

A. int a = -1; a = a >>> 8;
B. byte a = -1; a = (byte)(a >>> 5);
C. int a = -1; a = a >> 5;
D. int a = -1; a = a >>> 32;

Answer: BCD

why? the book says >>> will have a positive result?
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i thibk answer sshd be b and c

b will be negative cause int is again converted back byte
hence higher order bytes r removed
hence answer becomes negative

a>>>5

first of all a is converted to int

as int a is represented as :: 1111 1111 1111 1111 1111 1111 1111 1111

now a>>> 5 will make a : 0000 0111 1111 1111 1111 1111 1111 1111

now a is converted to byte (a = (byte)(a>>>5))

hence a = 1111 1111

or a = -1
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In case B, a>>>5 is certainly positive: but it's the cast from the intermediate int result to a byte that makes the final result negative.


In case D, the shift of 32 bits turns out to be a a shift of 0 bits. That's because a is an int and only the rightmost 5 bits of the shift operand (32) are taken. A >>> shift of 0 leaves a (-1) unchanged, therefore the result is negative.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic