Java: Prefix/postfix of increment/decrement operators?

O_O picture O_O · Mar 24, 2011 · Viewed 94.7k times · Source

From the program below or here, why does the last call to System.out.println(i) print the value 7?

class PrePostDemo {
     public static void main(String[] args){
          int i = 3;
          i++;
          System.out.println(i);    // "4"
          ++i;             
          System.out.println(i);    // "5"
          System.out.println(++i);  // "6"
          System.out.println(i++);  // "6"
          System.out.println(i);    // "7"
     }
}

Answer

Spidy picture Spidy · Mar 24, 2011
i = 5;
System.out.println(++i); //6

This prints out "6" because it takes i, adds one to it, and returns the value: 5+1=6. This is prefixing, adding to the number before using it in the operation.

i = 6;
System.out.println(i++); //6 (i = 7, prints 6)

This prints out "6" because it takes i, stores a copy, adds 1 to the variable, and then returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. The beauty of a postfix increment.

Then when you print out i, it shows the real value of i because it had been incremented: 7.