Learn AP Comp Sci

☰

Problem of the Day

Wednesday, September 30, 2026


Problem:

Consider the following method.

public static int randVals(int a, int b)
{
return (int) (Math.random() * (a+1) + b);
}

Which possible value of x may be returned as a result of the method call randVals(7, 2) ?

  1. 2 <= x <= 8
  2. 2 <= x <= 9
  3. 2 <= x < 8
  4. 2 <= x < 9

Show solution:

The correct answer is b. The call to Math.random() returns a double value between 0 (inclusive) and 1 (exclusive), or 0.9999999999999999. Multiplying that value by the (7 + 1) yields a value between 0 (inclusive) and 8 (exclusive), and adding 2 produces a value between 2 (inclusive) and 10 (exclusive). Finally, casting that double result as an int removes any digits after the decimal point, giving a value between 2 (inclusive) and 9 (inclusive).