Right shift with zero fill operator in Java (>>>) only working with "int" not "byte"

1.1k Views Asked by At

I write a program in Java to use the right shift with zero fill (>>>) operator. For the following program everything is good.

class First
{
        public static void main(String[] args)
        {
                int b = -1;
                int c = b>>>2;
                System.out.println(b);
                System.out.println(c);
        }
}

Output is:

-1
1073741823

Everything is good in the above program. But if I write the same program for byte:

class First
{
        public static void main(String[] args)
        {
                byte b = -1;
                byte c = (byte)(b>>>2);
                System.out.println(b);
                System.out.println(c);
        }
}

Output is:

-1
-1

It looks like working of ">>" operator rather than ">>>". My expected output was:

-1
63 

Please explain the concept behind it.

1

There are 1 best solutions below

0
On

Before each operation Java converts byte, short or char operand (variable, or constant both) to int. Then after the operation executes.

byte b = 2, c = 3;
byte d = b * c; //Compilation error

Before multiplication operation both b and c gets converted in int. so the result was int. We tried to store int in byte d, which results compilation error.

Same thing happens with shift operators too.

int c = b>>>2;

First b gets converted int. Then shift operation occurs with int. Final result is an int. As David Wallace says: "So the zeroes end up being in much more significant bits than the two leading bits of a byte".