Question related to Postfix and Prefix

publicstaticvoid main(String[] args)

{

int x = 0, y = 1, z = 2;

x = x++;

y = --y;

z = ++x + 4;

System.out.println("x =" + x);

System.out.println("y =" + y);

System.out.println("z =" + z);

}

Run the code out and you will find out that the final result is x = 1, y = 0, and z = 5. Expected output should be x = 2, y = 0, z = 6.

My question is

Why when the statement x = x++; executed, the value of x remain as 0?

x++ is postfix but it seem that it was never evaluated based on debugger.

x only become 1 when the statement z = ++x + 4;

The prefix work like normal but postfix is a bit unexpected.

Need an expert to explain this to me.

Thanks.

[1010 byte] By [Max102a] at [2007-11-26 22:54:24]
# 1

Regarding the problem with x, writing code like

x = x++;

is a bad idea. It just doesn't work as expected of the postfix operator. In short, here's how it is:

1. The variable for the postfix operator is evaluated (x = 0) and stored temporarily

2. x++ gets evaluated and the result is stored back to x (x = 1)

3. x (on the left side) gets assigned the value from step 1 (x = 0), which is the original value of the variable before the postfix operator is applied.

Therefore, x = x++ will always result in the same original value.

aberrant80a at 2007-7-10 12:18:16 > top of Java-index,Java Essentials,Java Programming...