I ran the following code snippet
int n=0;
for(int m=0;m<5;m++){
n=n++;
System.out.print(n)}
I got the output as 00000 when i expected 01234. Can someone explain why
Thanks in advance
n = n++
increments n
, then sets n
to the value it had before you incremented it. Use either:
n++;
or
n = n + 1;
but don't try to do both at once. It doesn't work.
n=n++;
should be just n++;
or n=n+1;
(or even n=++n;
if you want)
n++
does the increment but will return the value of n
before the increment took place. So in this case you're incrementing n
, but then setting n
to be the value before the increment took place, effectively meaning n
doesn't change.
The ++
operator can either be used as prefix or postfix. In postfix form ( n++
) the expression evaluates to n
, but in the prefix case ( ++n
) the expression will evaluate to n+1
. Just using them on their own has the same outcome though, in that n
's value will increment by 1.
When you have a ++, the operator can either be BEFORE or AFTER the variable. Likewise, the addition will occur before or after the operand is executed. If the line were to have read:
n = ++n;
Then it would have done what you would have expected it to do.
Since it doesn't seem to have been mentioned previously, you can also use
n += 1;
if you really like assignment operators.
n = ++n;
would also work :-) But it is useless to assign a variable to itself. In order to increment n, just use
n++;
or
++n;
Java uses value of a variable in the next instance on post increment.
In the code snippet, the loop execute for the first time picks up n=0 and increments at the operand. But the incremented value will be reflected on next occurrence of n not in current assignment hence 0 will be set to n one more time. I think this is because n=n++ is ATOMIC operation.
So the n is set 0 always.
To avoid this either you do pre-increment [++n] or +1 [n+1] where your reference get updated immediately.
Hope this answers your question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.