int i = 1;
System.out.println(i++ + ++i);
Why is this 4 given the following:
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.
It is evaluated left-to-right:
i++
is evaluated.
i
is incremented by 1, so it's now 2
1
, as the initial value of i
is returned++i
is evaluated
i
is incremented by 1, so it's now 3
3
, as the value after incrementing is returnedi++ + ++i
is evaluated
i++
was evaluated to 1++i
was evaluated to 34