Java: Prefix/postfix of increment/decrement operators?

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.

Leave a Comment