Please explain why output of
byte c = (byte) (-512);
System.out.print(c);
is 0
.
Please explain why output of
byte c = (byte) (-512);
System.out.print(c);
is 0
.
The range of byte in Java is -128 to 127
. Since -512 is not in the range, the compiler will ask for explicit typecasting. Hence, you have to cast the -512 (an integer) to byte. What happens when the program runs is that, JVM just removes the upper 24 bits to fit -512 in 8 bits.
-512 = 11111111111111110000001000000000 (int)
(byte) -512 = 00000000 (byte) //truncated the upper 24 bits// = 0