Its correct answer is 22. But I am getting 24. Where am I wrong? I evaluate the assignment operator += in last as it has the lowest precedence

Viewed 66
class Output
{    
    public static void main (String[] args)   
    {
        int a = 5;
    
        a += 5+ (++a) + (a++);
        System.out.print(a);
    }
}

Evaluation:

a += 5 + (++a) + (a++)

=> a+= 5 + 6 + (a++) [++a :increment value of a and then use it. So:increment a = 6, then use a=6]

=> a+= 5 + 6 + 6 [a++ :use and then increment value of a. So: use a=6, then increment a=7]
    
=> a+= 11 + 6
    
=> a+= 17
    
=> a = a+17
    
=> a = 7 + 17
    
=> a = 24
2 Answers

The += operator, like all compound operators, evaluates the variable on the left first, before evaluating all other operands, and before any operations are actually performed. This is specified by the JLS, Section 15.26.2:

If the left-hand operand expression is not an array access expression, then:

  • 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.

(bold emphasis mine)

That means that a is evaluated (and saved) to 5 on the left side before the a++ and ++a are evaluated on the right side. The right side does evaluate to 17, but because the left side is still 5, the sum is 22, not 24.

The expression

a += 5 + (++a) + (a++);

is equivalent to

a = a + 5 + (++a) + (a++);

Meaning that the new assigned value of a is the sum of the operands from right to left (because of left-to-right associativity) evaluated in the following way:

  • take the variable a: evaluated as 5
  • add the constant 5
  • increment the variable a and then evaluate the result: 6
  • evaluate the variable a and then increment it. The value used in the sum will be the evaluated value: 6

The sum is 22.

Related