AP CSA Unit 1 Day 3: Error Spotting Assignment

Unit 1 Advanced (Cycle 2) Day 3 of 28 Advanced

Spotting the Error: Variable Assignment

Section 1.2 — Variables and Data Types

Key Concept

Error-spotting questions present code with a subtle mistake and ask you to identify which line causes a compile error, runtime error, or produces unexpected output. Common variable assignment errors include: assigning a double to an int without casting, using a variable before initialization, redeclaring a variable in the same scope, and assigning incompatible types. The strategy is to check each statement against Java's type rules systematically rather than reading the code casually.

A student writes the following code. Which line will cause a compile-time error?

Line 1: int count = 10; Line 2: double price = 5; Line 3: int total = count * price; Line 4: System.out.println(total);

Which line causes the error?

Answer: (C) Line 3

Trace the types:

Line 1: Valid. int assigned an int literal.

Line 2: Valid. int 5 is widened to double 5.0 automatically.

Line 3: ERROR. count * price is int * double = double. Assigning a double to an int requires an explicit cast. Java does not allow automatic narrowing.

Fix: int total = (int)(count * price);

Why Not the Others?

(A) Assigning an int literal to an int variable is perfectly valid.

(B) Assigning an int value to a double is widening conversion, which Java performs automatically.

(D) If the code reached this line, printing an int would work fine. But the error on line 3 prevents compilation.

Common Mistake

Java automatically widens (int to double) but never automatically narrows (double to int). When an int and double are multiplied, the result is always double, which cannot be stored in an int without an explicit cast.

AP Exam Tip

Error-spotting questions require you to check each line for type compatibility. The most common compile error is trying to store a wider type (double) in a narrower type (int) without casting.

Review this topic: Section 1.2 — Variables and Data Types • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

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