Unit 3 Cycle 1 Day 18: Method Design and Return Values
Share
Method Design and Return Values
Section 3.6 — Writing Methods
Key Concept
Well-designed methods have a clear purpose, appropriate parameters, and a well-chosen return type. A method should do one thing and do it well. When deciding between void and non-void, consider whether the caller needs a result. Methods that answer questions (is, has, get) should return values; methods that perform actions (set, add, remove) may be void. On the AP exam, you may need to determine the correct return type for a method based on how it is used in the calling code, or identify when a return statement is missing.
Consider the following class.
What does new StringHelper("banana").countChar("a") return?
Answer: (C) 3
"banana": b(0) a(1) n(2) a(3) n(4) a(5). Three characters equal "a" at indices 1, 3, 5. Returns 3.
Why Not the Others?
(A) There are 3 a's in "banana", not 1.
(B) 2 would miss one of the three a's.
(D) 6 is the total length of the string, not the count of a's.
Common Mistake
This method uses substring to extract single characters and compares with .equals(). This is correct because substring returns a String, and Strings must be compared with .equals().
AP Exam Tip
When counting characters in a String, you can use substring(i, i+1).equals(ch) or charAt(i) == ch.charAt(0). Both work but the substring approach is more common on the AP exam.