Unit 1 Cycle 1 Day 25: String Method Chains and Edge Cases
Share
String Method Chains and Edge Cases
Section Mixed — Review: Strings
Key Concept
The equals() method and the == operator behave differently for reference types. The == operator checks whether two references point to the exact same object in memory (reference equality). The equals() method checks whether two objects have the same content (value equality). For the String class, equals() compares character sequences. For other classes, the behavior of equals() depends on whether the class overrides it — the default implementation from Object behaves the same as ==.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) true
This code reverses the string and checks if it is a palindrome:
Loop: i starts at 6 (last index), goes down to 0. Each iteration appends the character at index i.
i=6: substring(6,7) = "r". i=5: "a". i=4: "c". i=3: "e". i=2: "c". i=1: "a". i=0: "r".
rev: "racecar" — the same as the original.
s.equals(rev): "racecar".equals("racecar") is true.
Why Not the Others?
(B) The reversed version of "racecar" is "racecar" because it is a palindrome. So .equals() returns true.
(C) The code prints the result of s.equals(rev), which is a boolean. It does not print the string itself.
(D) When i = 6, substring(6, 7) is valid because index 7 is the exclusive end and s.length() is 7. No out-of-bounds exception occurs.
Common Mistake
Students worry about substring(6, 7) on a 7-character string. This is valid because the end index in substring can equal length(). The exclusive end means it grabs the character at index 6, which is the last character.
AP Exam Tip
This palindrome-checking pattern is very common on the AP exam. Recognize the reverse-and-compare approach. Also note: substring(i, i + 1) extracts exactly one character as a String, which is how you get individual characters when building a reversed string.