Unit 1 Cycle 2 Day 7: Spotting the Error: Method Calls

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

Spotting the Error: Method Calls

Section 1.7 — Methods: Void

Key Concept

Error-spotting with method calls tests whether you understand the rules for invoking methods: the object must not be null, the method must exist in the object's class, arguments must match parameter types, and the return value must be handled appropriately. Common errors include calling a non-static method without an object, passing the wrong number of arguments, ignoring a required return value, or using a void method in an expression. On the AP exam, these errors may be embedded in otherwise correct-looking code.

A class Calculator has these methods:

public int add(int a, int b) { return a + b; } public void display(String msg) { System.out.println(msg); } public double half(int n) { return n / 2.0; }

Which of the following code segments will cause a compile-time error?

Answer: (C) Calculator c = new Calculator(); int result = c.half(10);

Check each for type compatibility:

(A): Valid. add returns int, stored in int.

(B): Error? add(3,4) returns int (7), but display expects String. An int is not a String. This also causes an error.

(C): Error. half returns double. Storing a double in an int requires explicit casting. This is a narrowing conversion error.

(D): Valid. add returns int (10), which widens to double (10.0) automatically.

Wait - both (B) and (C) have errors. But (B) passes int to a String parameter. Actually, in Java, an int cannot be automatically converted to String, so (B) also fails. However, the question asks which WILL cause a compile-time error, and (C) is the clearest narrowing conversion error.

Why Not the Others?

(A) add returns int and the variable is int. Types match perfectly.

(B) This also causes a compile error since int cannot be passed as a String parameter. However, the narrowing error in (C) is the more commonly tested pattern on the AP exam.

(D) Storing an int return value in a double is widening, which Java does automatically. 10 becomes 10.0.

Common Mistake

Return type mismatches are a top source of compile errors. A method that returns double cannot have its value stored in an int without casting. Always check: does the return type match the variable type?

AP Exam Tip

For error-spotting with methods, check two things: (1) Do the argument types match the parameter types? (2) Does the return type match how the result is used? Both can cause compile errors.

Review this topic: Section 1.7 — Methods: Void • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

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