0

I have the following code:

System.out.println(0b11111111);
System.out.println((byte) 0b11111111);

First row prints

255

and the second row prints

-1

Please, can someone explain me why the results are different? How does (byte) casting change 0b11111110 number that it becomes -1?

Thank you!

Ihor Dobrovolskyi
  • 1,241
  • 9
  • 19

1 Answers1

5

The range of the byte type is -128 to 127. Since 255 is not a valid byte value, the binary number 11111111 is -1 when cast to byte.

If you don't cast 0b11111111 to byte, it remains (by default) an int, and 255 is a valid int value.

Eran
  • 387,369
  • 54
  • 702
  • 768