-6

Maybe I'm missing out but I can't figure out why I am getting the result 2 in this code:

i = 1;
i = i-- - --i;
System.out.println(i);
Antonio
  • 24
  • 4

1 Answers1

3

In i = i-- - --i you have:

  • i--, a post-decrement, which retrieves the current value of i (1) and then decrements i to 0
  • -
  • --i, a pre-decrement, which decrements i again and retrieves the updated value, -1

So you end up with i = 1 - -1 which is 2.


Needless to say, this sort of thing shows up on (silly) Java tests and such, but should never appear in production code.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875