Behavior of different compilers when adding bytes

byte b1 = 3; byte b2 = 0; b2 = (byte) (b2 + b1); // line 3 System.out.println(b2); b2 = 0; b2 += b1; // line 6 System.out.println(b2); 

In line 3, this is a compiler error, if we do not cast the result to a byte, this may be because the result of addition is always int and int does not fit into bytes. But, apparently, we do not need to enter the type in line 6. Are both statements, line 3 and line 6 equivalent? If not, then what else is wrong?

+5
source share
2 answers

Yes, two lines are equivalent, but they use different parts of the language, and they are covered by different parts of JLS. Line 3 is the normal + operator applied to bytes that have been upgraded to int , giving the result int . This must be done before you can assign it to the byte variable.

Line 6 is a compound assignment operator, as described in JLS Section 15.26.2 :

At run time, an expression is evaluated in one of two ways. If the left operand expression is not an array access expression, you must complete four steps:

  • First, the left operand is evaluated to create a variable. If this evaluation completes abruptly, then the assignment expression abruptly terminates for the same reason; the right operand is not evaluated and assignment is not performed.
  • Otherwise, the value of the left operand is stored, and then the right operand is evaluated. If this evaluation completes abruptly, the assignment expression abruptly terminates for the same reason and no assignment occurs.
  • Otherwise, the stored value of the left variable and the value of the right operand are used to perform the binary operation specified by the compound assignment operator. If this operation completes abruptly, the assignment expression abruptly terminates for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left variable , it undergoes the conversion of the set of values ​​(Sec. 5.1.13) into the corresponding standard value (not the value of the extended value of the exponent), and the result of the conversion is stored in the variable.

This is the last part (highlighted) that makes it different.

In fact, the beginning of the section shows equivalence:

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.

+10
source

Java was having problems with operations and conversions with integral types. Best tip: use int whenever you can. Avoid byte/short/char , explicitly convert them to int before any calculations.

-2
source

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


All Articles