Possible Duplicate:
What is the difference between a += b and a =+ b , also a++ and ++a?
What is x after “x = x++”?
In Test1 i increments its value by 1 and return old value and keep its incremental value in i variable. But in Test2 i increments its value by 1 and return its old value and the increment also occurred. Are they make a copy of i for the increment which is not assigning in the i variable. What is the operational step in Test2.
Test1
int i = 0;
System.out.print(i++);
System.out.print(i);
Output 01
Test2
int i = 0;
i = i++;
System.out.println(i);
Output 0
The statement i = i++ has well-defined behavior in Java. First, the value of i is pushed on a stack. Then, the variable i is incremented. Finally, the value on top the stack is popped off and assigned into i. The net result is that nothing happens -- a smart optimizer could remove the whole statement.
i = i++; is the tricky construct, what it really does is something like the following:
int iOld = i;
i = i + 1;
i = iOld;
You want to use only i++; as a standalone statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With