Why after executing such a code

int a = 0; a += a++; 

Does a write 0 , not 1 ?

  • Not equivalent. = and += differ significantly in behavior in order to consider the behavior of these examples separately. - AnT pm

2 answers 2

Expression

 a += a++; 

by definition, the += operator += equivalent to

 a = a + a++; 

In Java, the calculation of such expressions and the moments of occurrence of side effects of operators are uniquely ordered. Operands of binary operators are calculated from left to right:

  1. The left part of the assignment operator is trivial.
  2. The right side of the assignment statement is calculated: the expression a + a++ .
  3. To do this, the left operand of this subexpression is first calculated: a . The value of a at this moment is 0 . So the value of the left operand is 0 .
  4. Then the right operand of this subexpression is calculated: a++ . The value of a at this moment is 0 and when calculating a++ value of a increases by 1. However, the result of the postfix increment is by definition the initial value of a , that is, 0 .
  5. Now binary + calculated, that is, the whole sub-expression a + a++ . It gives the result 0 ( 0 + 0 ). Notice that at this point, the variable a already has the value 1, obtained in step 4.
  6. Then assignment is performed: the result of the calculation of the right-hand side, that is, 0 , is entered into the variable a . This is the final value of a .

Thus, formally, the variable a for some instant "managed" to get the value 1 at step 4, but then its value was again returned to 0 by the assignment operator at step 6

Note that if the expression a = a + a++ eventually puts 0 into a , the expression a = a++ + a will put a into 1 .

    1. We read the specification: jls-15.14.2 :

      The value of the variable is the value of the variable before the new value is stored.

    2. We read about priorities .

    The result: first, a++ calculated in a itself is now 1 , but the result of the increment operation itself will be the original value of a , i.e. 0 ; as a result, the expression reduces to a += 0; and in a will be 0 .

    • Information on the reference to "priorities" is simplified to such an extent that it is grossly incorrect. "Operators with higher precedence are relatively low."? No way! Despite the fact that ++ has a higher priority than += , the left part += in this example will be calculated before ++ . The link to jls-15.14.2 contains valid inofrmatsiyu. - AnT
    • @AnT hmm, I just thought it was obvious that += ++ transformed into = + ++ , so I didn’t write about it. - Suvitruf pm