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

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

Output: 0

Please can you people explain? It is really confusing

  • 1
    `i--` is value before decrement (11), then updates `i` to 10. `++i` increments `i` back to 11 first and result is that value. `11 - 11` is 0. Do that again for the expression in the `println()` statement, i.e. `0 - 0` is 0. If you want a more *complex* expression, see my answer to this question: [Incrementor logic](http://stackoverflow.com/q/33120663/5221149) – Andreas Aug 15 '16 at 01:57

2 Answers2

2
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.

Nick Zuber
  • 5,467
  • 3
  • 24
  • 48
1

i starts at 11, and you "use" that value and then decrement i to 10. So your state is:

  • Expression => 11 - ++i
  • i = 10

Then you increment i so your state is

  • Expression => 11 - i
  • i = 11

11 - 11 = 0.

Note that in C/C++ this would be undefined behavior, but in Java it is predictable.

John3136
  • 28,809
  • 4
  • 51
  • 69