I came across the following on a mock exam recently, and was a bit lost as to why the answer given is 25, 25 according to the order of operations, and what I might be missing from the specification that gives the details as to why.
public class Test {
public static void main(String[] args) {
int k = 1;
int[] a = {1};
k += (k = 4) * (k + 2);
a[0] += (a[0] = 4) * (a[0] + 2);
System.out.println(k + " , " + a[0]);
}
}
Just looking at line 6 above I substitute the appropriate values, and get the following:
k = k + (k = 4) * (k + 2);
I evaluate the parenthesis first, which indicates k has first been assigned to the value of 4, and subsequently is added to the number 2, giving the total of 6. This is how I interpret that:
k = k + 4 * 6;
Now this is where it gets confusing. According to the order of operations I get the following, which would be correct given the previous expression:
k = k + 24;
In my thinking at this point k should be 4 because that was the new assignment, but the answer is actually 25, and not 28. Apparently compound operators have some order of precedence I'm not understanding, or my substitution principles are not correct.