AP® Computer Science A · Unit 2 · Topic 2.10
Building and Reversing Strings in a Loop
Building a string in reverse means adding each new character to the front of the result instead of the back. Checking a palindrome means comparing characters from both ends of the string inward until you reach the middle.
To reverse a word in a loop, you walk through it from the first character to the last, but each character gets stuck onto the front of a growing result string, not the back. Picture a stack: the first letter you process ends up buried at the bottom, and the last letter you process sits on top, at the front of the final string. That is why reversal by loop feels like a stack unloading itself — whatever went in last comes out first.
Checking a palindrome works differently: you do not build anything new, you compare. Keep an index i starting at 0 and an index j starting at length - 1. Compare charAt(i) to charAt(j). If they match, move i forward and j backward, and repeat. If every pair matches by the time i and j meet or cross, the string reads the same forwards and backwards. The loop stops once i ≥ j, since going further would just recheck pairs you already confirmed.
This topic sits right after basic string-building loops and right before loops that transform input, because it combines both ideas: one version of the loop builds a new string, the other scans an existing one with two moving indices. The extension case — ignoring spaces and capitalization — connects forward to string methods like toLowerCase and replace, since cleaning the string before comparing is what makes checks like 'A man a plan a canal Panama' succeed instead of failing on a technicality.
Key terms
- Reversal by prepending
- Building a reversed string by adding each new character to the front of the result instead of the end.
- Two-pointer comparison
- Using one index starting at the front and one at the back, moving them toward each other to compare pairs.
- Palindrome
- A string that reads the same forwards and backwards once case and spacing are ignored.
- Normalization
- Converting a string to a consistent form, such as lowercase with no spaces, before comparing it.
Watch it explained
- How it worksHow does adding each character to the front instead of the back reverse a word?
- Worked exampleTrace building the reverse of JAVA one character at a time.
- Worked exampleFind whether RACECAR is a palindrome by comparing characters from both ends inward.
- Going furtherWhat changes when the palindrome check has to ignore spaces and capital letters?
Check yourself
End of topic.