3

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.

my name is GYAN
  • 1,269
  • 13
  • 27
  • The type of `(b >>> 2)` is `int`. So the zeroes end up being in much more significant bits than the two leading bits of a `byte`. – Dawood ibn Kareem Jan 16 '17 at 09:35
  • 1
    @David Wallace But b is a byte. The operator is operating on byte. Although after operation it returns int, but before that it becomes 63. Although 63 in int. May be I am wrong, but I am confused.. – my name is GYAN Jan 16 '17 at 10:15
  • Why do you say that "before" the operation it becomes 63? Nothing is 63 until after the operation. The `>>>` operator acts on `int` expressions, not `byte`, so the conversion happens before the operation. – Dawood ibn Kareem Jan 16 '17 at 17:00

1 Answers1

0

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".

my name is GYAN
  • 1,269
  • 13
  • 27