posted 22 years ago
The behavior of the shift operator is fairly obvious when working with 32 bit integers. However, the behavior of the shift operator is not entirely obvious when working with smaller primitive types such as byte, short, and char. That's because the shift operator promotes the operands to int primitives before doing the shift. For example, you would expect the following code to print a value of 127.
byte b = -1;
b = (byte)(b>>>1);
System.out.println(b);
Instead, the result is -1.
To produce a value of 127, you actually have to shift the byte 25 times to the right. Try running the following.
I think I will add the above to my mock exam. Thanks for the idea.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>