Search code examples
javaoperatorspost-increment

What is x after "x = x++"?


What happens (behind the curtains) when this is executed?

int x = 7;
x = x++;

That is, when a variable is post incremented and assigned to itself in one statement? I compiled and executed this. x is still 7 even after the entire statement. In my book, it says that x is incremented!


Solution

  • x does get incremented. But you are assigning the old value of x back into itself.


    x = x++;
    
    1. x++ increments x and returns its old value.
    2. x = assigns the old value back to itself.

    So in the end, x gets assigned back to its initial value.