reverse and setCharAt: In-Place Modifications
What you'll learn: How to flip an entire character sequence backward and swap individual characters without creating new String objects.
The Core Idea
Unlike immutable Strings, StringBuilder lets you modify the character sequence directly. Two powerful in-place operations are reverse(), which flips the entire content backward, and setCharAt(), which replaces a single character at a specific position—all without allocating new memory for intermediate results.
Think of a StringBuilder like a whiteboard with letters written on it. Instead of erasing the board and writing a new sentence (what String would do), you can simply flip all the letters backward or change one letter in place.
reverse(): Flip It All
The reverse() method inverts the entire character sequence from end to start:
StringBuilder sb = new StringBuilder("hello");
sb.reverse();
System.out.println(sb); // "olleh"
This operation happens in-place—no new object is created. The method returns the same StringBuilder instance for method chaining.
setCharAt(): Swap One Character
The setCharAt(int index, char ch) method replaces the character at a specific index:
StringBuilder sb = new StringBuilder("hello");
sb.setCharAt(0, 'H'); // Replace 'h' with 'H'
System.out.println(sb); // "Hello"
The index must be valid (0 to length-1) or you'll get an IndexOutOfBoundsException. Unlike append() or insert(), setCharAt() returns void—it can't be chained.
Why This Matters
These methods shine when you need algorithmic transformations. Reversing strings for palindrome checks, toggling case character-by-character, or building encoded messages all benefit from in-place modifications. No garbage is created, and performance stays optimal even with large sequences.
Key Takeaway:
reverse() flips the entire StringBuilder content backward, while setCharAt() replaces individual characters—both modify the existing object without creating new instances, making them efficient for transformations.