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"
}
}
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.
This prints out "6" because it takes i, stores a copy, adds 1 and 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 beautfy of a postfix increment.
Then when you print out i, it shows the real value of i because it had been incremented. 7
Think of
++i
andi++
as SIMILAR toi = i+1.
But it is NOT THE SAME. Difference is wheni
gets the new increment.in
++i
, increment happens immediately.but if
i++
is there increment will happen when program goes to next line.Look at code here.
This will result non ending loop. because
i
will be returned with original value and after the semicolon i will get incremented but returned value has not been. Thereforei
will never actually returned as an incremented value.Why wouldn't the variable have been updated?
The lines where you don't do anything with i make no difference.
Notice that this is also true for assignments: