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 mi
In this answer, I will only consider the k
case, it is the same for the array.
int k = 1;
k += (k = 4) * (k + 2);
// k += (k = 4) * (k + 2)
// 1 += (k = 4) * (k + 2)
// 1 += 4 * (k + 2) with k = 4
// 1 += 4 * 6 with k = 4
// k = 25
The tricks here:
k +=
captures the value of k
before doing the calculation. +=
is called a compound assignment operator. Quoting the relevant part of the JLS:
the value of the left-hand operand is saved and then the right-hand operand is evaluated.
k = 4
returns the assigned value, so 4.