<分区>
我最近不得不参加 Java 考试,并且想知道我做错的其中一题。问题如下:
以下代码在没有任何参数的情况下运行时会打印什么...
public class TestClass {
public static int m1(int i){
return ++i;
}
public static void main(String[] args) {
int k = m1(args.length);
k += 3 + ++k;
System.out.println(k);
}
}
答案是 1 到 10 之间的数字。 我原来的答案是 7,而他们说正确的答案是 6。
我的逻辑:
m1 sets k to 1, as it's ++i and thus gets incremented prior to returning.
then the += is unrolled, making: 'k = k + 3 + ++k'.
++k is executed, making k 2.
Replace the variables with their value: 'k = 2 + 3 + 2'
k = 7.
但是,他们表示为 k = 1 + 3 + 2。 谁能解释为什么在执行++k 之前先替换变量?