3

In this example:

class Test3 {
    public static void main(String[] args) {
        byte mask = 1;
        for(mask <<= 7; mask != 0; mask >>>= 1) {
            System.out.print(mask + " ");
        }
    }
}

I was expecting the output to be -128 64 32 16 8 4 2 1, instead i received an infinite recursive loop of -1. If i change the type of the mask variable to be int, the program behaves normally. Could you please explain me why I am having this particular output? Thank you in advance for your time to help me!

ardavirus
  • 87
  • 5
  • 1
    No recursion here, you meant to say infinite loop. – Maroun Apr 25 '14 at 11:03
  • 1
    Actually, it starts like `-128 -64 -32 -16 -8 -4 -2 -1 -1 -1 ...`. – Gassa Apr 25 '14 at 11:04
  • @Maroun yes infinite loop is what i meant, thank you for correcting me. – ardavirus Apr 25 '14 at 11:06
  • 1
    And with both `mask >>>= 1` and `mask >>= 1`, which is strange. As for why, I would also like to know. – Gassa Apr 25 '14 at 11:08
  • @Gassa at first loop 'mask' will be 1000 0000 that is -128, at the second my intention was to be 0100 0000 that is 64. I used the >>> operator not the >>. Am I mistaken at this as well? – ardavirus Apr 25 '14 at 11:09
  • 3
    Googled the cause: `byte` is promoted to `int` before the operation. See here: http://stackoverflow.com/questions/3948220/behaviour-of-unsigned-right-shift-applied-to-byte-variable. – Gassa Apr 25 '14 at 11:11
  • @Gassa Thank you, that was very helpful. So far I haven't seen any constructive use of the byte type in java. I admit I am newbie but hey it's byte. – ardavirus Apr 25 '14 at 11:19

1 Answers1

3

All byte operations in Java occur by converting a byte into an integer and when the operation finishes it converts the integer back to a byte. The conversion into a byte just removes the highest byte from the int. Hence the int value 0xff00 would be converted into the byte value 0x00. Now to your example:

When you shift the byte value 1 seven times to the right, you get in the first place the integer value:

0x0001

which is shift to:

0x0080

and converted back to the byte value by removing the highest byte:

0x80 == 100000000 == -128

Now you shift the byte value 1 position to the right, which first converts the byte into the integer:

0xff80

and then shifts in a 0 to the most significant bit (position 31) which results in:

0x7fc0

Converted the int value back to a byte by removes the highest byte results in:

0xc0 == 11000000 == -64

And this continuous til to the byte value

0xff == 11111111 == -1

and will never end.

Harmlezz
  • 7,972
  • 27
  • 35