Java: Prefix/postfix of increment/decrement operators?

前端 未结 10 1403
不知归路
不知归路 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
    
    0 讨论(0)
  • 2020-11-22 07:54

    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

    0 讨论(0)
  • 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. 
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:00

    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"
    
    0 讨论(0)
提交回复
热议问题