how come the above code is printing 11,11 instead of 11,12
can any fellow rancher unveil the logic behind it.
Check carefully at line #3 you are assigning 11 to i and incrementing i by 1 but when you have assigned the value of i it's again 11 even after increment. I mean to say that post-increment doesn't matter's here because you are assigning the value to i itself.
In the statement i = i++, the increment of i does take place when i++ is evaluated.
However, the value of a postincrement is the value of the value before the increment takes place.
the postincrement i++ has the value of i before the increment takes place, even though i++ is going to increment i. In this case if i is 11, i++ will increment i's value to 12.
However, because i is on the left-hand side of the assignment statement, i is going to be given the value of the right-hand side.
The value of the right-hand side is the value of i++.
So i = i++, no matter what i is, will not change i. Just to conclude assignment done before incrementing the value. so value of i will not change. More over you can try just by replace i=i++ with i++ and see the answer you are looking for.
Line 2: i is incremented first (prefix notation, i becomes 11), then the value of the expression is assigned to i (i still 11). This is a "double assignment", if you think about it, but both assignments yield the same result.
Line 3: the value of the expression is computed first (postfix notation, the expression "i++" is 11), then i is incremented (becomes 12). Then the expression value (which is 11) is assigned to i (i then gets set back to 11). Again, this is a "double assignment".
I can understand how someone might be confused and think that the answer might be 12, 12. But how could it be 11, 12? The println() statements in your example have no code in between them. How could the value possibly change? Maybe your code sample has the statements in the wrong order. Anyway, the "trick" is what I explained above.
This is a very tricky and very good question. I am sure this kind of thing confuses many programmers.
Thank you very much for contributing this question.
Good job, Nitin!! [ July 13, 2006: Message edited by: Douglas Chorpita ]
SCJP 1.4 - 95%
Joined: May 17, 2006
i = i++ means first i=i and then i will be incremented. but where it will be incremented? and how can we see it?
Joined: May 09, 2006
You can change the code. Instead of:
You can break it down into its parts:
temp will prove that i was incremented to 12. [ July 13, 2006: Message edited by: Douglas Chorpita ]
Joined: May 17, 2006
Thank you very much for your time and effort to explain me. Now i got the point...