AP CSA Unit 1 Day 23: Compareto Prefix Strings
Share
compareTo with Prefix Strings
Section 1.11 — Strings: Comparison
Key Concept
The compareTo() method compares strings lexicographically (dictionary order) based on Unicode values. When one string is a prefix of another, the shorter string comes first: "app".compareTo("apple") returns a negative number. The exact return value is the difference in lengths when one is a prefix of the other. For strings that differ at a specific position, the return value is the difference between the Unicode values at that position. The AP exam tests whether you know the sign of the result, not the exact numerical value.
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 negative
How compareTo handles different-length strings:
r1: "APP".compareTo("APPLE"). The first 3 characters match (A, P, P). "APP" is shorter, so it comes first. Result is negative (3 - 5 = -2, the difference in lengths).
r2: "APP".compareTo("APR"). Compare character by character: A=A, P=P. Then P(80) vs R(82). P comes before R, so result is negative (80 - 82 = -2).
Why Not the Others?
(B) Both comparisons yield negative results. "APP" comes before both "APPLE" and "APR" alphabetically.
(C) "APP" is a prefix of "APPLE", so it comes first (negative). It also comes before "APR" because P < R.
(D) r1 is not zero because the strings are not equal ("APP" has 3 characters, "APPLE" has 5).
Common Mistake
When one string is a prefix of another, compareTo returns the difference in lengths (negative if the caller is shorter). When characters differ, it returns the difference in Unicode values at the first mismatch point.
AP Exam Tip
For compareTo, the AP exam usually just asks whether the result is negative, zero, or positive. A shorter string that is a prefix of a longer one is always "less than" (negative result).