College Board Unit 1
How it works
Java widens int to double automatically, but narrowing from double to int requires an explicit (int) cast, and that cast truncates rather than rounds. Math.random() returns a double in the range 0.0 up to but not including 1.0. To produce integers from low to high inclusive you multiply by the count of values and shift: (int)(Math.random() * (high - low + 1)) + low.
Build a random range by multiplying first, casting to int second, and adding the lower bound last.
Common error
Casting too early throws away the fractional part that the scaling needed, collapsing the range.
Worked example
Java
int total = 11;
int count = 4;
System.out.println((double) total / count);Output
2.75The cast changes an operand before division. Casting the already-truncated result would be too late.
Exercises
1.3.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
System.out.println((int) -3.9);
System.out.println((double) (11 / 4));Show solution
Output
-3
2.0Narrowing truncates toward zero. The parentheses perform integer division before widening.
1.3.2 · Write code
Write an expression for a random integer from 4 through 9 inclusive. Show its smallest and largest possible results. Use r = 0.0 and r = 0.999999 to test the endpoints of the expression.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
double r = 0.0;
System.out.println((int) (r * 6) + 4);
r = 0.999999;
System.out.println((int) (r * 6) + 4);
// In use: (int) (Math.random() * 6) + 4