Byte unary operation
java
Solution
Whenever you perform a binary operation between two operands of different types, one of the operands is promoted to the higher type. And then the result of the operation is of that type.
So, in your case, the `byte` type `a` is first promoted to an `int`, since `1` is an `int` type. And then after the addition operation, the result is of type `int`. Now, since you cannot assign an `int` to a `byte`, you need to do a typecast to remove the compiler error:
byte a = 2;
a = a + 1; // Error: Cannot assign an int value to byte
a = (byte)(a + 1); // OK
Now, in case of Compound Assignment Operator, the typecasting is done implicitly for you. The expression:
a += 1
is internally converted to:
a = (byte)(a + 1);
This is specified in JLS - §15.26.2 Compound Assignment Operator:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
Similar is the case with prefix 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.
Problem
We all know that in Java these operators: ``` a++; ++a; a += 1; a = a + 1; ``` do the same thing, they simply add 1 to variable 'a' However why these statements are not all true, what is the principle behind this? ``` byte a = 1; a++; ++a; a += 1; a = a + 1; // This line will result to a compile time error ``` Why?