Java: Prefix/postfix of increment/decrement operators?

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

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

提交回复
热议问题