javapost-incrementpre-incrementassociativity

Why values of i and j are 2 after the execution of statement " j= i++ + ++i"?


The code I used is

int i=0, j=0; j=i++ + ++i;

And the output I got is i=2 and j=2

Could anyone explain how this happens!


Solution

  • The expression is evaluated in below steps:

    Step 1 : j = i++ + ++i; => j = 0 + ++i; step result i = 1 and j = 0 (post increment will update the value but returns the old value)

    Step 2 : j = 0 + ++i; => j = 0 + 2; step result i = 2 and j = 0 (pre increment will update the value and returns the updated value)

    Step 3 : j = 0 + 2; => j = 2; step result i = 2 and j = 2 (direct addition and assign value to j)