Unit 1 · Using Objects and Methods
Casting and Math.random
Practice mode with 15 Java-focused questions, immediate answer checks, and explanations.
What casting and math.random covers
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.
Where students lose points
Off-by-one range errors dominate. Students write (high - low) instead of (high - low + 1) and silently lose the top value of the range. The other frequent error is casting too late: (int)(a / b) still performs integer division first if a and b are both ints, whereas (double) a / b promotes before dividing.
How it shows up on the AP exam
Unit 1 content that shows up as "which expression generates a random integer from 5 to 15 inclusive" style questions, and inside FRQs that ask for randomized behavior. Knowing where the parentheses go is most of the battle.
For practice use only.
Casting and Math.random MCQ Practice
Practice AP CSA casting and Math.random: int to double promotion, explicit (int) truncation, and building the exact random integer range the question asks for.
Answered 0 of 15
Choose one answer.
