user3292797 user3292797 - 3 months ago 6
Java Question

output of expression in ( i-- - ++i) in java

int i = 11;
i = i-- - ++i;

System.out.println( i-- - ++i );


Output:
0

Please can you people explain?
It is really confusing

Answer
i = 11;
i = i-- - ++i;

Before we do anything, i holds the value of 11.

When we do i--, we actually decrease the value of i by 1, but this doesn't take into effect until after we use it here.

// i = 10;
i = 11 - ++i;

So now i holds the value 10.

Now, we subtract 10 from ++i. Since we're pre incrementing here, i's value is increased by 1 before we get to it.

// i = 11;
i = 11 - 11;

So now i holds the value 11.

And finally, we assign 11 - 11 back to i.

// i = 0;
i = 0;

So we end up with a value of 0.