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
Product of two bytes will not necessarily fit into a byte. So Java needs you to tell it that you know what you are doing and confirm that in case of overflow you will get the low-order bits.
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
.