AP CSA Unit 1 Day 18: Compareto Ordering
Share
compareTo() for String Ordering
Section 1.11 — Strings: Comparison
Key Concept
The return statement exits a method and optionally sends a value back to the caller. A method declared with a return type (e.g., int, String) must return a value of that type on every possible execution path. A common AP exam error involves conditional returns where one branch is missing a return statement. The returned value can be used directly in expressions: System.out.println(obj.getValue() * 2) calls the method and multiplies the result. Methods that return void can use return; with no value to exit early.
Consider the following code segment.
Which of the following is true about the values of r1 and r2?
Answer: (A) r1 is negative and r2 is zero
compareTo() returns:
• A negative number if the calling String comes before the argument alphabetically.
• Zero if the Strings are equal.
• A positive number if the calling String comes after the argument.
r1: "APPLE".compareTo("BANANA") is negative because 'A' comes before 'B' in Unicode.
r2: "APPLE".compareTo("APPLE") is 0 because the Strings are identical.
Why Not the Others?
(B) "APPLE" comes before "BANANA" alphabetically, so compareTo returns a negative value, not positive.
(C) r1 compares different Strings and cannot be zero. "APPLE" and "BANANA" are not equal.
(D) Both parts are wrong. r1 is correctly negative, but r2 is zero because the two Strings are identical.
Common Mistake
Students mix up the sign. Think of it as subtraction: "APPLE" - "BANANA" where A(65) - B(66) = -1, so the result is negative. When the calling String comes first alphabetically, the result is negative.
AP Exam Tip
You do not need to know the exact number compareTo returns. The AP exam only asks whether the result is negative, zero, or positive. Negative means the caller comes first; positive means the caller comes second; zero means they are equal.