0

Please explain why output of

byte c = (byte) (-512);
System.out.print(c);

is 0.

  • What is confusing you about it? Do you know what is [range of `byte`](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) and [integer overflow](https://en.wikipedia.org/wiki/Integer_overflow)? – Pshemo Jul 20 '15 at 18:24
  • possible duplicate of [How does Java handle integer underflows and overflows and how would you check for it?](http://stackoverflow.com/questions/3001836/how-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo) – byako Jul 20 '15 at 18:25
  • Yes I do..its -128 to 127 but why is the output 0 – NIKHIL NAGRALE Jul 20 '15 at 18:27
  • Try to print results for `-129`,`-130` ... `-512` and observe what happens. – Pshemo Jul 20 '15 at 18:29
  • Got it..If it goes out of range the final value will be value%256(modulo) correct? – NIKHIL NAGRALE Jul 20 '15 at 18:42

1 Answers1

1

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
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Vivin
  • 1,327
  • 2
  • 9
  • 28