1

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?

Community
  • 1
  • 1
Surfer on the fall
  • 721
  • 1
  • 8
  • 34

9 Answers9

12

These are the pre- and post-increment operators. This behavior is exactly correct.

  • i++ returns the original value.
  • ++i returns the new value.
David Harkness
  • 35,992
  • 10
  • 112
  • 134
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

When you do i++ the incrementation doesn't happen until the next instruction. It's called a post increment.

Maciej Trybiło
  • 1,187
  • 8
  • 20
2
System.out.println(i++);

It should first print value of i then increment the i. Its post order increment.

  • i++ -> post order increment
  • ++i -> pre order increment
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
2
++i will print 1
i++ will print 0 
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
2

i++ means return i, then increment. Hence ++ after i.

++i means increment i, then return. Hence ++ in front of i

Petter Nordlander
  • 22,053
  • 5
  • 50
  • 84
1
  • i++ => evaluation then increment;
  • ++i => increment then evaluation.

Think about a for loop - i is incremented after every iteration.

moonwave99
  • 21,957
  • 3
  • 43
  • 64
1

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

mjgpy3
  • 8,597
  • 5
  • 30
  • 51
1

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)

Argeman
  • 1,345
  • 8
  • 22
1

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.

Tushar Paliwal
  • 301
  • 4
  • 11