AP CSA Unit 1 Day 28: Comprehensive Review

Unit 1 Foundation (Cycle 1) Day 28 of 28 Foundation

Comprehensive Unit 1 Review

Section Mixed — Review: All Unit 1

Key Concept

This Unit 1 final review integrates all fundamental concepts: variable declaration and initialization, primitive types and their ranges, operator precedence, casting and type promotion, String methods and comparison, wrapper classes, Math class operations, random number generation, and object construction. On the AP exam, expect questions that combine two or three of these concepts in a single code segment. The key to success is recognizing which rule applies at each step and not making assumptions about Java's behavior.

A student writes the following method intended to return a random integer between low and high, inclusive.

public static int randBetween(int low, int high) { return (int)(Math.random() * high) + low; }

Which of the following best describes the error in this method?

Answer: (C) The range multiplier should be (high - low + 1) instead of high.

The correct formula is: (int)(Math.random() * (high - low + 1)) + low

The student multiplies by high instead of the range size (high - low + 1).

Example: If low = 5, high = 10, the student's code produces (int)(Math.random() * 10) + 5, giving values from 5 to 14 instead of 5 to 10.

Why Not the Others?

(A) The placement of the cast is fine. Casting before adding low correctly truncates the random portion, then shifts the range. Moving the cast would not fix the core problem.

(B) Math.random() returns [0.0, 1.0), which is correct. Adding 1 would shift the range to [1.0, 2.0), breaking the formula entirely.

(D) While the code does produce values outside the intended range, the maximum is (high - 1) + low, not high + low. This option misidentifies the specific error.

Common Mistake

The multiplier in Math.random() must be the count of possible values: high - low + 1. For [5, 10], there are 6 possible values (5, 6, 7, 8, 9, 10), so multiply by 6, which is 10 - 5 + 1.

AP Exam Tip

Error-spotting questions require you to identify what is wrong, not just whether the code compiles. Read each answer choice and test it mentally with specific values. If low = 5 and high = 10, what does each version produce?

Review this topic: Section Mixed — Review: All Unit 1 • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.