Question:
Consider the following code snippet:
int x = 5;
int y = 3;
int z = 2;
int result = x + y * z - x / z;
System.out.println(result);
What value will be printed to the console? Explain how the expression is evaluated step-by-step.
Answer:
The value that will be printed to the console is 13
.
Explanation:
The expression x + y * z - x / z
is evaluated according to the operator precedence rules in Java, where multiplication and division take precedence over addition and subtraction.
Step 1: Evaluate y * z
Since both y
and z
are integers, the multiplication operator *
performs integer multiplication. The result of y * z
is 3 * 2
, which equals 6
.
Step 2: Evaluate x / z
Similar to the previous step, the division operator /
performs integer division. The result of x / z
is 5 / 2
, which evaluates to 2
(integer division discards the fractional part).
Step 3: Evaluate x + (y * z) - (x / z)
Substituting the evaluated values from steps 1 and 2, we have 5 + 6 - 2
.
Step 4: Perform addition and subtraction The addition and subtraction operators have left-to-right associativity, so we evaluate the expression left to right.
5 + 6
equals 11
.11 - 2
equals 9
.Therefore, the value stored in the result
variable will be 9
.
Finally, System.out.println(result)
prints 9
to the console.