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

后端 未结 14 2498
暖寄归人
暖寄归人 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 05:05

    I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.

    The code will work like this:

    int a=5,i;
    
    i=++a + ++a + a++;            /*a = 5;
                                    i=++a + ++a + a++; =>
                                    i=6 + 7 + 7; (a=8); i=20;*/
    
    i=a++ + ++a + ++a;           /*a = 5;
                                    i=a++ + ++a + ++a; =>
                                    i=8 + 10 + 11; (a=11); i=29;*/
    
    a=++a + ++a + a++;            /*a=5;
                                    a=++a + ++a + a++; =>
                                    a=12 + 13 + 13;  a=38;*/
    
    System.out.println(a);        //output: 38
    System.out.println(i);         //output: 29
    

提交回复
热议问题