int i = 11;
i = i-- - ++i;
System.out.println( i-- - ++i );
Output: 0
Please can you people explain? It is really confusing
int i = 11;
i = i-- - ++i;
System.out.println( i-- - ++i );
Output: 0
Please can you people explain? It is really confusing
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
.
i
starts at 11, and you "use" that value and then decrement i to 10. So your state is:
11 - ++i
Then you increment i so your state is
11 - i
11 - 11 = 0.
Note that in C/C++ this would be undefined behavior, but in Java it is predictable.