Consider the following code segment. What is printed as a result of executing the code segment?
int x = 4;
x += 3;
x *= 2;
x--;
System.out.println(x);
6713147, then 14, and the final decrement leaves 13.
Explanation
Each compound assignment uses the current value of x. Adding 3 raises the starting value, multiplying by 2 doubles that result, and x-- decreases the variable by 1. Tracing in order keeps an old value out of a later step.
- A is not correct: this applies the decrement to
7but skips the multiplication, andx *= 2runs first and doubles the stored value. - B is not correct: this is the value of
xafter only the first update, so the trace stops beforex *= 2andx--have run. - D is not correct: this is the value reached after the multiplication, but
x--still runs and decreases the variable by1before the value is printed.