Course outline · 0% complete

0/29 lessons0%

Course overview →

StringBuilder and string drills

lesson 10-1 · ~11 min · 27/29

Quiz

Warm-up from lesson 2-2: word.toUpperCase() runs but word prints unchanged afterward. Why?

StringBuilder

Strings are immutable (lesson 2-2), so result += piece cannot extend the string — it builds a whole new one, copying everything so far. Do that in a loop and n appends cost 1 + 2 + ... + n copies: the O(n²) pattern from lesson 10-0, hiding in one innocent line. Interviewers watch for exactly this. StringBuilder is a mutable text buffer that appends without recopying, keeping the whole build O(n):

StringBuilder sb = new StringBuilder();
sb.append("Ja");      // O(1) amortized (lesson 10-0)
sb.append("va");
sb.length();           // 4
sb.reverse();          // in place
sb.toString();         // back to a String

Also useful: sb.insert(0, "x"), sb.deleteCharAt(i), sb.charAt(i), and constructing pre-loaded with new StringBuilder("seed"). The classic one-liner interview move: reverse a string with new StringBuilder(s).reverse().toString().

Code exercise · java

Run this. A StringBuilder grows, gets a prefix inserted, reverses in place, and a loop builds a comma-joined line without the O(n²) trap.

The palindrome pattern

A palindrome reads the same forward and backward (racecar, level). With your tools this is two lines:

String reversed = new StringBuilder(s).reverse().toString();
boolean isPal = s.equals(reversed);

Remember from lesson 2-2: compare Strings with .equals, never ==. The StringBuilder detour exists because String itself has no reverse method.

Drill sequence you should now be able to do cold: reverse a string, check a palindrome, count characters with the HashMap idiom from lesson 7-2, and join pieces with a separator like the example above.

Code exercise · java

Your turn. Print the word reversed, then print `racecar is a palindrome: true` by building the reversed copy of the second word and comparing with equals.