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 sends
println
the value I had prior to this line of code (6), and then increments I (to 7).This is my answer. Some of you may find it easy to understand.
I know this has been answered, but thought another explanation may be helpful.
Another way to illustrate it is:
++i
will give the result of thenew i
,i++
will give the result of the originali
and store thenew i
for the next action.A way to think of it is, doing something else within the expression. When you are printing the current value of
i
, it will depend upon whetheri
has been changed within the expression or after the expression.i
is evaluated (changed) before the result is calculated. Printingi
for this expression, shows the changed value ofi
used for this expression.i
is evaluated after the result in calculated. So printingi
from this expression gives the original value ofi
used in this expression, buti
is still changed for any further uses. So printing the value fori
immediately after the expression, will show the new incremented value ofi
. As the value ofi
has changed, whether it is printed or used.If you kept a consistent pattern and included print lines for all the values:
It prints 7 for the last statement, cos in the statement above, it's value is 6 and it's incremented to 7 when the last statement gets printed
Maybe you can understand better Prefix/postfix with this example.
Well think of it in terms of temporary variables.
Now,
is equivalent to