Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top