Whenever you perform a binary operation between two operands of different types, one of the operands advances to a higher type. And then the result of the operation is of this type.
So, in your case, the byte a type is first promoted to int , since 1 is an int type. And then after the add operation, the result is of type int . Now, since you cannot assign an int to byte , you need to do typecast to remove the compiler error:
byte a = 2; a = a + 1;
Now, in the case of Compound Assignment Operator, type casting is done implicitly for you. Expression:
a += 1
internally converted to:
a = (byte)(a + 1);
This is indicated in JLS - ยง15.26.2 Continent assignment operator :
The compound assignment expression E1 op = E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type E1, except that E1 is evaluated only once.
Similarly, in the case of incremental increment operators and postfix increment operators.
According to JLS - ยง15.15 Unary operators :
The type of the prefix increment expression is the type of the variable.
source share