后增量 (i++) 和前增量 (++i) 运算符如何在 Java 中工作?

问题描述:

你能向我解释一下这段 Java 代码的输出吗?

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.println(i);

两种情况的输出都是 20

The output is 20 in both cases

这有帮助吗?

a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)

a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)

重点是 ++a 增加值并立即返回它.

The main point is that ++a increments the value and immediately returns it.

a++ 也会增加值(在后台)但返回变量的未更改值 - 看起来它稍后执行.

a++ also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.