# Shift Operator Question

Yan Bai
Ranch Hand
Posts: 125
Hello everybody,
I am brand new in this forum and Java programming, hope to get helps from all of you.
I was stuck by the following question in Mock exam.
Code:
----------------------------------------------
class J {
public static void main (String[] s) {
byte b = 0;
b += ~b >>> 1;
System.out.println(b);
}
}
-----------------------------------------------
<I>
The entire four bits are shifted to the right and a zero replaces the most significant bit of the most significant byte; however, only the value of the least significant byte is printed.
</I>
More detailed explaination and examples are very appreciated.

Dan Chisholm
Ranch Hand
Posts: 1865
Yan,
The binary representation of ~0 is as follows.
11111111
Before the shift to the right, the left hand operand is converted to a 32 bit int. It is then shifted to the right one bit and zero is shifted into the most significant bit. The result is as follows.
01111111 11111111 11111111 11111111
If the above were printed as an int, the value would be Integer.MAX_VALUE. However, the compound assignment operator includes an implicit cast to the type of the left hand operand, so the result is cast to a byte by keeping the least significant byte and by throwing away the three most significant bytes. The result is as follows.
11111111
It is the two's compliment representation of -1.
The following are some additional examples of two's compliment representation of small integers.
1=00000001
0=00000000
-1=11111111
-2=11111110
-3=11111101
-4=11111100
I hope the above helps.

Yan Bai
Ranch Hand
Posts: 125
Dan,
Thanks for clarifying this, and thanks for providing the mock exams, which are very useful for the preparation.
-Yan

May Pat
Ranch Hand
Posts: 32
I have a question on the sample question.

This code compiled fine and returns a result.
However, if I do:

I got a compiler error saying possible loss of precision. Why the first one doesn't? I understand that when doing shift operation, bitwise operation or add operation, byte will be promoted to int then the operation is performed. The result is returned as int. If we want to assign it to a smaller primitive type, we need to explicitly cast the result. Does the reason that the original code work because += operation does some implicite casting? Thank you.

Corey McGlone
Ranch Hand
Posts: 3271
Originally posted by May Pat:
Does the reason that the original code work because += operation does some implicite casting?

Yes. All compound assignment operators perform an implicit cast. Check out the JLS, §15.26.2 Compound Assignment Operators for more juicy details.
Corey