Question 261
What is printed?
String w1 = "banana";
String w2 = "band";
String w3 = "ban";
int r1 = w1.compareTo(w2);
int r2 = w2.compareTo(w3);
System.out.println((r1 > 0) + " " + (r2 < 0) + " " + (r1 + r2 > 0));Main Solution
Step-by-step evaluation:
r1 = w1.compareTo(w2) compares "banana" to "band".
- Both strings share the prefix
"ban". The 4th character of"banana"is'a'and the 4th character of"band"is'd'. 'a'has ASCII value 97;'d'has ASCII value 100.- So
r1 = 97 - 100 = -3(a negative value).
r2 = w2.compareTo(w3) compares "band" to "ban".
- Both share the prefix
"ban"."band"has a 4th character'd', while"ban"has no 4th character (it is shorter). - In Java,
compareToreturns the difference in lengths when one string is a prefix of the other:4 - 3 = 1(a positive value). - So
r2 = 1.
Evaluating the three boolean expressions:
(r1 > 0): Is-3 > 0? false(r2 < 0): Is1 < 0? false(r1 + r2 > 0): Is-3 + 1 > 0? Is-2 > 0? false
The printed output is: false false false
Answer: A
Teacher Explanation
String.compareTo() returns a negative integer if the calling string lexicographically precedes the argument, zero if equal, and a positive integer if it follows. "banana" precedes "band" (because 'a' < 'd' at index 3), giving a negative r1. "band" follows "ban" (because it is longer and "ban" is a prefix), giving a positive r2. Since r1 is negative and r2 is positive but |r1| > r2, their sum is still negative. All three boolean expressions evaluate to false.
Education Coach Advice
AP Exam Strategy: When evaluating compareTo, always compare character-by-character from left to right. The first position where the characters differ determines the sign of the result. If one string is a prefix of the other, the shorter string comes first (returns negative from the longer string's perspective). Never rely on string length alone to determine lexicographic order.
Traps
Common traps:
- Option D (true true true): Students may incorrectly assume
"banana" > "band"because "banana" is longer, but lexicographic comparison is character-by-character, not by length. At index 3,'a' < 'd', so"banana"actually comes before"band". - Option C (false true false): Students might think
r2 < 0because"band"is longer than"ban"and confuse the direction of comparison, butw2.compareTo(w3)returns positive (w2 follows w3), not negative. - Option B (true false false): A reversal of the r1 sign error — thinking
"banana" > "band"due to length.
Answer images

