Somebody please explain me . Why below program produces 16 ?
public static void main(String[] args) {
byte b1 = 60, b2 = 60;
byte product = (byte) (b1 * b2);
System.out.println(product);
}
Integer overflow issue.
60 * 60 = 3600 which is 111000010000 in binary form.
byte is a 8-bits data form. Therefore it will truncate into 8 bits of the data which is equivalent to 00010000 which is 16 in decimal. Hope this answer your question.
This is because a byte
can only store numbers ranging from -128
to 127
, and 60 * 60 = 3,600
, which is way over the byte's maximum storage, so it creates an Integer Overflow error. To fix this, you could use:
public static void main(String[] args) {
byte b1 = 60, b2 = 60;
int product = b1 * b2;
System.out.println(product);
}
A Byte can have 8 bits (binary digits), and 3600 is 111000010000
in binary form. (12 bits), so, the 4 extra bits in the beginning are dropped so it can fit in a byte, changing the binary to 00010000
instead of 111000010000
, and 000100002 = 1610, so you get the output 16 instead of the desired 3600.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With