Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying two bytes

Tags:

java

byte

Can somebody explain me why I can't to multiply two bytes in this way?

byte a = 1;
byte b = 1;
byte c = a*b;

or

byte a = 1;
byte b = 1;
short c = a*b;

Why I have to do that in this way?

byte a = 1;
byte b = 1;
byte c = (byte)(a*b);

or

byte a = 1;
byte b = 1;
int/double/float/long c = a*b;
like image 747
Mateusz Avatar asked May 11 '15 18:05

Mateusz


1 Answers

When performing math with bytes, binary numeric promotion takes place, as specified by the JLS, Section 5.6.2.

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  2. Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    • If either operand is of type double, the other is converted to double.

    • Otherwise, if either operand is of type float, the other is converted to float.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to type int.

(emphasis mine)

That forces you to assign to a type that is at least as wide as int or to cast back to byte.

like image 85
rgettman Avatar answered Oct 28 '22 05:10

rgettman