Search code examples
javaintpost-incrementpre-increment

Pre and post on Java. Not taking effect?


int x = 12;     
int y = 15;      
while (y >= 0)     
{      
     x = x--;     
     y = --y;     
}      
System.out.print(x);     

This prints out 12 and I'm guessing x is never changed because it's stored before the post (x--) takes effect, but why does x-- never take effect?


Solution

  • -- in x-- does take effect. However, you do not see it, because you assign the value of pre-decrement x right back into x.

    Here is what happens when you do x = x--:

    • The value of x gets stored into a temporary space (say, tempX)
    • One is subtracted from x
    • New value is assigned back into x
    • Once the right-hand side has finished computing, tempX is assigned back to x

    This produces the overall effect of x not being changed.

    The effect of y = --y differs because the value of the expression --y is the same as the value of y after the decrement, so the overall effect is the same as --y.