Difficulty: Easy
Correct Answer: i = 0
Explanation:
Introduction / Context:
The expression explores numeric casting in Java. Math.random()
returns a double in the half-open range [0.0, 1.0). Casting such a value to an integer truncates toward zero, which determines the only possible result.
Given Data / Assumptions:
Math.random()
∈ [0.0, 1.0).int
performs truncation, not rounding.
Concept / Approach:
Any double d
with 0.0 ≤ d < 1.0 becomes 0 when cast to int
. There is no chance for 1 or negative numbers from this specific cast because the range excludes 1.0 and does not include negatives.
Step-by-Step Solution:
Verification / Alternative check:
If you intended random integers 0 or 1, you would write (int)(Math.random() * 2)
. For 1..10, use (int)(Math.random()*10) + 1
.
Why Other Options Are Wrong:
Common Pitfalls:
Confusing truncation with rounding; forgetting that 1.0 is excluded from Math.random()
range.
Final Answer:
i = 0
Discussion & Comments