How do the post increment (i++) and pre increment (++i) operators work in Java?

后端 未结 14 2533
暖寄归人
暖寄归人 2020-11-21 04:45

Can you explain to me the output of this Java code?

int a=5,i;

i=++a + ++a + a++;
i=a++ + ++a + ++a;
a=++a + ++a + a++;

System.out.println(a);
System.out.p         


        
14条回答
  •  花落未央
    2020-11-21 04:51

    Presuming that you meant

    int a=5; int i;
    
    i=++a + ++a + a++;
    
    System.out.println(i);
    
    a=5;
    
    i=a++ + ++a + ++a;
    
    System.out.println(i);
    
    a=5;
    
    a=++a + ++a + a++;
    
    System.out.println(a);
    

    This evaluates to:

    i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
    

    so i is 6 + 7 + 7 = 20 and so 20 is printed.

    i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)
    

    so i is 5 + 7 + 8 = 20 and so 20 is printed again.

    a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
    

    and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.

提交回复
热议问题