Java:操作顺序,增量后澄清
// CODE 1
public class YourClassNameHere {
public static void main(String[] args) {
int x = 8;
System.out.print(x + x++ + x);
}
}
你好!
我知道上面的代码会打印 25。但是,我想澄清一下 x++ 如何使语句成为 8 + 9 + 8 = 25。
如果我们仅这样打印 x++,由于后增量,将打印 8 而 x 在内存中将是 9。
// CODE 2
public class YourClassNameHere {
public static void main(String[] args) {
int x = 8;
System.out.print(x++);
}
}
但是为什么在代码 1 中它最终变成了 9?
我提前感谢您的时间和解释!
回答
这里有一个很好的方法来测试等于 25 的原因是因为第三个x等于 9。
public class Main {
public static void main(String[] args) {
int x = 8;
System.out.println(printPassThrough(x, "first") + printPassThrough(x++, "second") + printPassThrough(x, "third"));
}
private static int printPassThrough(int x, String name) {
System.out.println(x + " => " + name);
return x;
}
}
结果
8 => first
8 => second
9 => third
25