Possible Duplicate:
pre Decrement vs. post Decrement
What is the difference between ++i and i++?
I've just realized that
int i=0;
System.out.println(i++);
prints 0 instead of 1. I thought that i was incremented and THEN printed. It seems that the contrary happens.
Why?
These are the pre- and post-increment operators. This behavior is exactly correct.
i++
returns the original value.++i
returns the new value.
When you do i++
the incrementation doesn't happen until the next instruction. It's called a post increment.
++i will print 1
i++ will print 0
System.out.println(i++);
It should first print value of i then increment the i. Its post order increment.
i++
means return i, then increment. Hence ++ after i.
++i
means increment i, then return. Hence ++ in front of i
i++
=> evaluation then increment;++i
=> increment then evaluation.Think about a for
loop - i
is incremented after every iteration.
The ++
after the variable defines a post-increment operation. This means that after you are done executing everything else on the line, then i
is increased. If you used ++i
the variable would be incremented before it is printed
As you can find here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html there are two incrementing operators: i++ and ++i. ++i does what you thought i++ would do. i++ increments the value after usage for other purposes (look into the link for more details)
Because the value given to the System.out.println(i++);
is assigned 0 first then it is incremented.
if you will attempt to do System.out.println(++i);
then it will display 1 to you.