Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

Here, the first two lines are valid but the last is not

         byte b = -128;

        byte b1 = 127;

        byte b2 = b>>>b1;//illegal

What is meant exactly by 8-bit signed? 128 in binary format would be 10000000 and -128 would need an extra bit for negative sign, where it would fit if all the 8 bits are occupied.

For int, there is an unsigned right shift operator, but that seems illegal with bytes, why is it so. Can overflow not be prevented in case of bytes.

1 Answer

0 votes
by (13.1k points)
  1. Just what it sounds like: There are 8 bits, holding 2^8=256 possible values. It’s signed, so the range is from -128 through 127. The most significant bit has a value of -128.

  2. In Java, binary numeric promotion occurs with operations such as b>>b1. Both types are promoted to int, and the result is an int. However, you can explicitly cast the result back to byte

Here is the cast:

Byte b2=(byte)(b>>>b1);

The documentation talks about binary numeric promotion:

 Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

If either operand is of type double, the other is converted to double.

Otherwise, if either operand is of type float, the other is converted to float.

Otherwise, if either operand is of type long, the other is converted to long.

Otherwise, both operands are converted to type int.

Want to learn Java? Check out the java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 18, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Feb 15, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...