AP CSA Unit 1 Day 22: Error Type Mismatch
Share
Error Spotting: Type Mismatch Chain
Section Mixed — Review: Types and Methods
Key Concept
Type mismatch chain errors occur when a sequence of operations progressively changes types in unexpected ways. For example, an int divided by an int produces an int, stored in a double as a .0 value, then cast back to int — each step may lose or preserve precision differently. The AP exam chains three or four such operations together, testing whether you track the type at each step correctly. The final answer depends on understanding exactly when conversions occur.
Consider the following code segment. Which line will cause a compile-time error?
Which line causes the error?
Answer: (C) Line 3
Check type compatibility on each line:
Line 1: Valid. int 10 widens to double 10.0.
Line 2: Valid. Math.pow(2, 3) returns 8.0 (double). The explicit cast (int) converts it to 8.
Line 3: ERROR. Math.sqrt(16) returns 4.0 (double). Assigning double to int without a cast is a narrowing error. Needs (int) cast.
Line 4: Valid (but tricky). 5 / 2 = 2 (integer division), then widens to 2.0. Not an error, just a logic trap.
Why Not the Others?
(A) Assigning int to double is widening, which Java does automatically.
(B) The explicit cast (int) converts the double from Math.pow() to int. This is valid.
(D) This compiles fine. 5 / 2 is integer division (result: 2), which widens to 2.0. Not an error, though the programmer probably wanted 2.5.
Common Mistake
Both Math.pow() and Math.sqrt() return double. Line 2 has a cast but Line 3 does not. Missing the cast when storing a double in an int is a compile error. Line 4 compiles but gives an unexpected result.
AP Exam Tip
On the AP exam, error-spotting questions often include a line that compiles but has a logic error (like Line 4). Do not confuse logic errors with compile errors. The question specifically asks about compile-time errors.