int i = 0; i = i++; System.out.println(i); // This prints 0
Snippet 2:
int i = 0; i = i; i++; System.out.println(i); // This prints 1
According to the definition of ++ postfix, the value should be used first and then incremented. So, I interpreted that both snippets should produce the same result. This doesn't seem to be the case. Can someone please explain.
The explanation for i = i++ is as follows: i++ is an expression, and as such, it has a value. The value of the expression "i++" is the value of i before the increment. If you did "j=i++" you'd expect j to be 10, right? Because you know that i++, as a post-increment operator, gets the value first and then increments.
So, the value of i++ is 10. Once the expression is evaluated to get that value, then the increment occurs. So now i is 11.
Finally after the i++ has done its bit, whatever is on the left side (in this case it happens to be i, but it would be the same if it were j), gets the value of the expression. No, that value isn't 11. It's 10. The value of i++ is i's value before the increment. It's 10.
But why will it print 0 for i = i++; I understand that i++ means: 1)first use it; in this case assign 0 to i and then 2)increment i by 1. The process of increment is done before printing. But still it prints 0.....Why ?? Please explain... [ December 19, 2005: Message edited by: Ravisekhar Kovuru ]
For those who are not still clear I am copying which is already somewhere on Javaranch.
Let's take a close look at what the line "i = i++;" does:
"i++" is evaluated. The value of "i++" is the value of i before the increment happens. As part of the evaluation of "i++", i is incremented by one. Now i has the value of 1; The assignment is executed. i is assigned the value of "i++", which is the value of i before the increment - that is, 0. That is, "i = i++" roughly translates to
int oldValue = i; i = i + 1; i = oldValue;
With other words, it is a common misconception that the increment is happening last. The increment is executed immediately when the expression gets evaluated, and the value before the increment is remembered for future use inside the same statement.
int i = 0; i = i++ + i++ + i++ + i++; System.out.println(i);
Output = 6.
Since it is post incrementer, assignment occurs before increment.
Step � 1 � The first i++ will execute like, I will be assigned to the value 0 and it gets incremented. Step - 2 � Since in step 1 the I value is incremented, it will be 1 now. So once again I will be assigned and increments happens. So now I value will be 0+1=1. Step � 3 � Same things happens, since an increment had happened the I value after step 2 will be 2. So 1+2 = 3. Step � 4 � Same thing happens, so 3+3 = 6.
I have a knack for fixing things like this ... um ... sorry ... here is a consilitory tiny ad: