Unit 1 Cycle 1 Day 11: Calling Void Methods
Share
Calling Void Methods
Section 1.7 — Methods: Void
Key Concept
The String class is a reference type in Java, meaning variables store references to objects rather than the values themselves. Key methods for the AP exam include length() (returns the number of characters), substring(start, end) (returns characters from index start up to but not including end), and indexOf(str) (returns the first occurrence index, or -1 if not found). Remember that string indices start at 0, and substring includes the start index but excludes the end index — this half-open range is a common source of off-by-one errors.
A class Printer has the following method.
Which of the following code segments will cause a compile-time error?
Answer: (B) Printer p = new Printer(); String result = p.printTwice("Hi");
The method printTwice has a void return type, meaning it does not return a value.
(B) tries to assign the result of printTwice to a String variable. Since the method returns nothing (void), there is nothing to assign. This causes a compile-time error.
All other options call the method correctly without trying to capture a return value.
Why Not the Others?
(A) This is a valid call. It creates a Printer object and calls printTwice with the String "Hi". No return value is expected.
(C) This is valid. "Hi" + "!" concatenates to "Hi!", which is a String. Passing it to a method expecting a String parameter is fine.
(D) This is valid. An empty String "" is still a String object and can be passed as an argument.
Common Mistake
You cannot store the result of a void method in a variable. void means the method performs an action (like printing) but does not return data. Writing String result = voidMethod() always causes a compiler error.
AP Exam Tip
When you see a method call on the AP exam, immediately check two things: (1) Does the return type match how the result is being used? (2) Do the argument types match the parameter types? These are the two most common method call errors.