AP CSA Unit 1 Day 12: Return Values
Share
Return Values and Method Calls
Section 1.8 — Methods: Return Values
Key Concept
String comparison in Java requires the equals() method, not the == operator. Using == compares whether two references point to the same object in memory, not whether the strings contain the same characters. The compareTo() method returns a negative number if the calling string comes before the argument alphabetically, zero if they are equal, and a positive number if it comes after. For case-insensitive comparison, use equalsIgnoreCase(). A common AP exam trap: "hello" == "hello" may return true due to string pooling, but this behavior is unreliable.
Consider the following method.
What is returned by the call mystery(17, 5)?
Answer: (A) 5
Substitute a = 17, b = 5:
a % b: 17 % 5 = 2 (5 goes into 17 three times = 15, remainder 2)
a / b: 17 / 5 = 3 (integer division truncates)
Result: 2 + 3 = 5
Why Not the Others?
(B) 6 might come from incorrectly computing 17 % 5 = 3. The remainder of 17 / 5 is 2, not 3. The quotient is 3.
(C) The return type is int, so the result cannot be 5.4. Both % and / with int operands produce int results.
(D) 3 is only the quotient part (17 / 5). The method adds the remainder (17 % 5 = 2) to the quotient, giving 2 + 3 = 5.
Common Mistake
Students often confuse % (remainder) and / (quotient). For 17 / 5: quotient is 3, remainder is 2. Notice that a % b + a / b effectively reconstructs the original division: quotient + remainder (though not the original number).
AP Exam Tip
When a method returns a value, trace the expression inside the return statement with the given arguments. Write down each intermediate value. On the AP exam, this is faster than trying to compute everything in your head.