我最近不得不做一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
答案是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 + …Run Code Online (Sandbox Code Playgroud)