Java: Prefix/postfix of increment/decrement operat

2018-12-31 07:53发布

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"
     }
}

9条回答
初与友歌
2楼-- · 2018-12-31 08:52
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 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

查看更多
怪性笑人.
3楼-- · 2018-12-31 08:53

Think of ++i and i++ as SIMILAR to i = i+1. But it is NOT THE SAME. Difference is when i 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.

int i = 0;
while(i < 10){
   System.out.println(i);
   i = increment(i);
}

private int increment(i){
   return i++;
}

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. Therefore i will never actually returned as an incremented value.

查看更多
墨雨无痕
4楼-- · 2018-12-31 08:56

Why wouldn't the variable have been updated?

  • Postfix: passes the current value of i to the function and then increments it.
  • Prefix: increments the current value and then passes it to the function.

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
查看更多
登录 后发表回答