Java: Prefix/postfix of increment/decrement operators?

前端 未结 10 1573
不知归路
不知归路 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:52

    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.

提交回复
热议问题