Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different compiler behavior when adding bytes

Tags:

java

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);

On line 3, it's a compiler error if we don't typecast the result to a byte -- that may be because the result of addition is always int and int does not fit into a byte. But apparently we don't have to typecast on line 6. Aren't both statements, line 3 and line 6, equivalent? If not then what else is different?

like image 829
Zohaib Avatar asked Oct 06 '11 22:10

Zohaib


1 Answers

Yes, the two lines are equivalent - but they use different parts of the language, and they're covered by different parts of the JLS. Line 3 is the normal + operator, applied to bytes which have been promoted to int, giving an int result. That has to be cast before you can assign it back to a byte variable.

Line 6 is a compound assignment operator as described in section 15.26.2 of the JLS:

At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.

It's the last part (as highlighted) that makes it different.

In fact, the start of the section shows the equivalence:

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.

like image 71
Jon Skeet Avatar answered Oct 22 '22 03:10

Jon Skeet