Joey van Gangelen Joey van Gangelen - 9 days ago 6
Java Question

Trouble understanding order of execution in a java algorithm (k= and ++k)

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?

Answer

Ok, you are correct in stating that the ++ operator has precedence over the += operator and therefore the += will not be unrolled until the ++ operation has been carried out .... however before any operation is carried out the interpreter first evaluates the operands of most operators and this is done from left to right.

So in your example, where k = 1,

k += 3 + ++k;

effectively is:

1 += 3 + ++k;

and then the ++k is evaluated as this has precedence and becomes:

1 += 3 + 2;

the + has precedence and becomes:

1 += 5;

and at this point the += is unrolled, which of course gives 6 ... QED