Search code examples
javaexpressionincrementoperator-keyword

strange expression evaluation order with unary increment operators for same variable in JAVA


int i = 1;
System.out.println(i++ + ++i);

Why is this 4 given the following:

  1. Expressions in Java are evaluated from left to right (after precedence)
  2. Post increment (i++) has higher precedence. So it should be 1 + 2.

I recommend deleting the question by a moderator, since the answer is simply (as per Joachim's comment) that the evaluation of expression in context of post increment operator includes any expression within the expression and not just the top one of the primary statement (sysout in this case). Given i++ is a statement in itself which increments a variable by 1 it gets already executed in sub-expression (i++) but returns i to parent expression. that was simply what I was not aware of.


Solution

  • It is evaluated left-to-right:

    1. i++ is evaluated.
      • i is incremented by 1, so it's now 2
      • the value of this expression is 1, as the initial value of i is returned
    2. ++i is evaluated
      • i is incremented by 1, so it's now 3
      • the value of this expression is 3, as the value after incrementing is returned
    3. the addition in i++ + ++i is evaluated
      • i++ was evaluated to 1
      • ++i was evaluated to 3
      • 1+3 is 4