Byte unary operation

We all know that in Java these operators:

a++; ++a; a += 1; a = a + 1; 

do the same thing, they just add 1 to the variable 'a'

However, why are these statements not all true, what is the principle of this?

 byte a = 1; a++; ++a; a += 1; a = a + 1; // This line will result to a compile time error 

Why?

+4
source share
2 answers

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; // Error: Cannot assign an int value to byte a = (byte)(a + 1); // OK 


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.

+3
source

a = a + 1;

This is due to the type of expression a = a + 1; . LHS is promoted to int , and then the add is performed. Then you try to set the int value for byte without casting.

Refer JLS 5.6.2

The primitive conversion extension (ยง5.1.2) is used to convert one or both operands, as specified in the following rules:

  • If one of the operands 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 int type.

a ++; ++ a;

Here type is the type of the variable. Again in accordance with JLS 15.15

The type of the prefix increment expression is the type of the variable.

The type of the prefix decrement expression is the type of the variable.

a + = 1;

According to JLS 15.26.2

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.

Therefore, here a += 1; equivalent to a = (byte)(a+1); since this is done implicitly.

0
source

Source: https://habr.com/ru/post/1491052/


All Articles