In Java (Math.random casting), what value is assigned to i in the statement below? int i = (int) Math.random();

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).
  • Cast to 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:

Let d = Math.random() → 0 ≤ d < 1 (int)d truncates toward 0 → 0 Therefore i = 0 always

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:

  • 1 or undetermined: contradict the defined range and truncation.
  • Compile error: the code is legal.
  • Negative: impossible from the domain.

Common Pitfalls: Confusing truncation with rounding; forgetting that 1.0 is excluded from Math.random() range.

Final Answer: i = 0

More Questions from Java.lang Class

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion