J.I · Java 25 practice question
Given this Java 25 code using a compound assignment on an array element, what does it print?
void main() {
int[] data = {10};
data[0] += (data[0] = 4);
System.out.println(data[0]);
}
Check answer and explanation
Correct answer: 14
Explanation
The current value of data[0] (10) is saved before the right-hand operand is evaluated, so 10 is added to the result 4, storing and printing 14.
Common trap
Assuming the right-hand assignment updates data[0] to 4 before the left-hand value is read leads to 4 + 4 = 8, which contradicts the specification. Thinking the inner assignment overwrites the final result ignores that the outer compound assignment still stores the sum back into data[0].
Source: JLS SE 25 §15.26.2. Compound Assignment Operators
Checked against the cited text on 2026-11-25.