Multiplying two bytes

后端 未结 2 2007
孤城傲影
孤城傲影 2021-01-12 22:09

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         


        
2条回答
  •  终归单人心
    2021-01-12 22:56

    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.

提交回复
热议问题