From the program below or here, why does the last call to System.out.println(i)
print the value 7
?
class PrePostDemo {
public
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:
i = 0;
test = ++i; // 1
test2 = i++; // 1
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
This is my answer. Some of you may find it easy to understand.
package package02;
public class C11PostfixAndPrefix {
public static void main(String[] args) {
// In this program, we will use the value of x for understanding prefix
// and the value of y for understaning postfix.
// Let's see how it works.
int x = 5;
int y = 5;
Line 13: System.out.println(++x); // 6 This is prefixing. 1 is added before x is used.
Line 14: System.out.println(y++); // 5 This is postfixing. y is used first and 1 is added.
System.out.println("---------- just for differentiating");
System.out.println(x); // 6 In prefixing, the value is same as before {See line 13}
System.out.println(y); // 6 In postfixing, the value increases by 1 {See line 14}
// Conclusion: In prefixing (++x), the value of x gets increased first and the used
// in an operation. While, in postfixing (y++), the value is used first and changed by
// adding the number.
}
}
Well think of it in terms of temporary variables.
i =3 ;
i ++ ; // is equivalent to: temp = i++; and so , temp = 3 and then "i" will increment and become i = 4;
System.out.println(i); // will print 4
Now,
i=3;
System.out.println(i++);
is equivalent to
temp = i++; // temp will assume value of current "i", after which "i" will increment and become i= 4
System.out.println(temp); //we're printing temp and not "i"