Promotion in Java?

Solution 1:

There's no + operator for byte. Instead, both operands are promoted to int, so you've got

byte = byte + byte
... becomes (widening to find + operator) ...
byte = int + int
... becomes (result of + operator) ...
byte = int 

... which then fails because there's no implicit conversion from int to byte. You need to cast:

byte a = 1;
byte b = 2;

byte c = (byte) (a + b);

Here are the actual rules for numeric promotion, from section 5.6.2 of the JLS:


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, using widening conversion (§5.1.2) to convert operands as necessary:

  • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
  • 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.

Solution 2:

You were provided with correct answer about automatic promotion to 'int'.

There is one more note about that - compound assignment operators behave as they have an implicit type case. Example:

byte b1 = 1;
byte b2 = 2;
b1 = b1 + b2; // compilation fails
b1 += b2; // compilation successful