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;
When performing math with byte
s, 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:
If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
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
.
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