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

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

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

    is

    i = 6 + 7 + 7
    

    Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.

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

    is

    i = 5 + 7 + 8
    

    Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.

提交回复
热议问题