0

Assume int x = 1;

System.out.println(x++ + x); ---> Output:3

System.out.println(x++ - x); ---> Output:-1

System.out.println(x-- + x); ---> Output:1

System.out.println(x-- - x); ---> Output:1

x = x++; 
System.out.println(x);  ---> Output:1

Can anyone please explain how post-increment works?
Note: All print statements are executed independently.

Chris
  • 26,361
  • 5
  • 21
  • 42
Mohamed Arshad
  • 89
  • 1
  • 1
  • 6
  • x-- returns 1 and then decrements to 0, then you add or subtract 0. – luk2302 Jan 30 '22 at 20:49
  • the pre and post (de)increment functionality dates back to an era where programmers used these operations to directly increment/decrement registers in the processor. When I'm thinking in a conscious way, I try to avoid these and use plain arithematic instructions which are easier to read. But when I'm up against a deadline or just trying to get something finished, I do still use them... I know, I'm bad :( – ControlAltDel Jan 30 '22 at 20:57

1 Answers1

1

When x is 1, x++ increments x to 2, but the expression returns the value before the increment (or decrement): 1.

x++ + x is equivalent to: 1 + 2.

x++ - x is equivalent to 1 - 2.

x-- + x is equivalent to 1 + 0.

x-- - x is equivalent to 1 - 0.

x = x++ is equivalent to x = 1.

Chris
  • 26,361
  • 5
  • 21
  • 42