I've had to do a Java exam recently, and was wondering about one of the questions I had wrong. The question was as follows:
What will the following code print when run without any arguments ...
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);
}
}
With the answers being a number between 1 and 10. My original answer was 7, whereas they state that the correct one is 6.
My logic:
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.
However, they state it as k = 1 + 3 + 2. Could anyone explain as to why the variable is replaced first, before performing the ++k?