Java: Prefix/postfix of increment/decrement operators?

前端 未结 10 1597
不知归路
不知归路 2020-11-22 07:17

From the program below or here, why does the last call to System.out.println(i) print the value 7?

class PrePostDemo {
     public          


        
10条回答
  •  旧巷少年郎
    2020-11-22 07:54

    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
    

提交回复
热议问题