Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying two byte numbers

Tags:

java

byte

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);

}
like image 904
Cataclysm Avatar asked Nov 29 '22 07:11

Cataclysm


2 Answers

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.

like image 138
Sky Avatar answered Dec 04 '22 20:12

Sky


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.

like image 35
Jojodmo Avatar answered Dec 04 '22 22:12

Jojodmo