Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

1.3: Casting and Math.random

Cast before division to preserve a fraction. Math.random returns a double from 0 inclusive to 1 exclusive; the integer range width is high - low + 1.

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.75

The 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.0

Narrowing 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
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic