The operands of +
undergo binary numeric promotion: that is, they are widened where necessary to make them compatible for addition. The rule is quite simple:
- If either operand is a double, widen the other to double
- If either operand is a float, widen the other to float
- If either operand is a long, widen the other to long
- Otherwise, widen them both to int
in the second case, it is effectively (int) b1 + 5
, the result of which is a non-compile-time constant int
. This can't be guaranteed to be in the range of byte
, so the compiler complains.
In the first case, both operands are compile-time constant ints, so the result is a compile-time constant int; the compiler can check that result is within the range of byte
, and so can implicitly narrow the result.