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?
The post
and pre
increment operators do operate on a temporary value which is getting assigned after the equation. Which means that
i = 0;
i = i++ // still 0
i = ++i // 1
Because the right hand side is temporary and do not reflect the left side before the assignment.
With your logic this would result in
int i = 0;
i = ++i // 2 - wrong.
Without any arguments means args.length = 0
int k = m1(args.length); m1 (0) = ++0 = 1
So k = 1
k += 3 + ++k;
k = k + 3 =4. ++k = ++1 = 2
So
4 + 2 = 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With