Building strings efficiently
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)In Java, every String object is immutable — its characters can never be modified after it is created. Appending one character at a time with s = s + c inside a loop quietly copies the entire string on every iteration, turning an O(n) loop into an O(n²) timeout.
Why String + in a loop is O(n^2), and how StringBuilder fixes it
StringBuilder is a changeable sequence of characters. Appending to it in a loop is O(n) overall, while joining Strings with + in a loop can cost O(n^2).
Because String is immutable, s = s + c copies the whole old string on every pass, so a loop costs O(n²). The code below counts the copies against StringBuilder.
Across n iterations, the number of characters copied is 1 + 2 + 3 + … + n = (n(n + 1))/2 = O(n²) time and O(n²) temporary garbage on the heap! (Note: in Java 9+, a single expression like a + b + c on one line is compiled into a fast invokedynamic recipe, so + outside a loop is fine; the O(n²) trap happens when s += ... sits inside a loop.)
Example 1 · Brute force: build a string with += in a loop (O(n²) time, O(n) space)
public class StringPlusBuildDemo { static long copiesWithStringPlus(int n) { long copies = 0; int currentLen = 0; for (int i = 0; i < n; i++) { copies += currentLen + 1; // New String copies old chars + 1 new char currentLen++; } return copies; }
public static void main(String[] args) { String s = ""; for (int i = 1; i <= 5; i++) { s += i; if (i < 5) s += "-"; } System.out.println("Built with String += : " + s); System.out.println("String += char copies for n=10,000 : " + copiesWithStringPlus(10_000)); }}Built with String += : 1-2-3-4-5 String += char copies for n=10,000 : 50005000
What this code does
- Each
s += ...creates a new String and copies the old characters, so for n = 10,000 characters it copies over 50 million. - The result is correct, but the work grows with n × n.
Example 2 · Optimal: build the string with a StringBuilder (O(n) time, O(n) space)
public class StringBuilderBuildDemo { static long writesWithBuilder(int n) { long writes = 0; for (int i = 0; i < n; i++) { writes++; // append writes only the new character } return writes; }
public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 5; i++) { sb.append(i); if (i < 5) sb.append("-"); } System.out.println("Built with StringBuilder : " + sb.toString()); System.out.println("StringBuilder char writes for n=10,000 : " + writesWithBuilder(10_000)); }}Built with StringBuilder : 1-2-3-4-5 StringBuilder char writes for n=10,000 : 10000
What this code does
- The text is the same, but each append writes only the new characters into a reusable buffer, so n = 10,000 needs 10,000 writes.
- A single
Stringis created at the end bysb.toString(). This is why StringBuilder is the standard tool for building text in a loop.
Example 3 · StringBuilder methods: append, deleteCharAt(length - 1), and reverse
public class StringBuilderMethodsDemo { // Removes adjacent duplicate letters using StringBuilder as a character stack static String removeAdjacentDuplicates(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); int len = sb.length(); if (len > 0 && sb.charAt(len - 1) == c) { sb.deleteCharAt(len - 1); // O(1) removal from the END of StringBuilder! } else { sb.append(c); } } return sb.toString(); }
public static void main(String[] args) { System.out.println("abbaca -> " + removeAdjacentDuplicates("abbaca"));
StringBuilder rev = new StringBuilder("stressed").reverse(); System.out.println("reverse('stressed') -> " + rev.toString()); }}abbaca -> ca
reverse('stressed') -> dessertsWhat this code does
- Deleting the last character of a
StringBuilder(sb.deleteCharAt(sb.length() - 1)orsb.setLength(len - 1)) shifts zero characters and runs in O(1) time, makingStringBuildera fast character stack! - On
"abbaca",'b'cancels'b'leaving"aaca", and then the second'a'cancels the first'a', leaving"ca".
Because String is immutable, s = s + c cannot append c to the end of s's existing character buffer. Instead, on iteration i, Java allocates a brand-new String of length i, copies all i - 1 characters from the old s, and adds c at the end.
StringBuilder is a mutable dynamic array of characters (just like ArrayList, it doubles its internal buffer when full). Calling sb.append(c) inside a loop is amortised O(1) per character, so building a string of length n and calling sb.toString() once at the end takes O(n) time and O(n) space.
s += cin a loop: copies 1 + 2 + … + n = O(n²) characters.sb.append(c)in a loop: amortised O(1) per append, O(n) total.sb.reverse(): reverses the builder's characters in place in O(n) time.sb.insert(0, c)orsb.deleteCharAt(0): shifts all characters right or left, costing O(n) per call — append at the end and callsb.reverse()once if building backwards!
char[] arrays for fixed-length in-place edits
When the output has the same length as the input, convert the string to a char[], edit it by index, and convert back once. The code below edits a string in place.
Using char[] lets you apply every in-place array technique (two-pointer swaps, range reversals) directly to strings.
Example 4 · In-place edits with char[] and O(1)-space palindrome check
public class CharArrayAndPalindromeDemo { static String toggleCase(String s) { char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c >= 'a' && c <= 'z') { chars[i] = (char) (c - 'a' + 'A'); } else if (c >= 'A' && c <= 'Z') { chars[i] = (char) (c - 'A' + 'a'); } } return new String(chars); }
static boolean isPalindrome(String s) { int left = 0; int right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; }
public static void main(String[] args) { System.out.println("toggleCase('Java-17!') : " + toggleCase("Java-17!")); System.out.println("isPalindrome('racecar'): " + isPalindrome("racecar")); System.out.println("isPalindrome('mentor') : " + isPalindrome("mentor")); }}toggleCase('Java-17!') : jAVA-17!
isPalindrome('racecar'): true
isPalindrome('mentor') : falseWhat this code does
s.toCharArray()gives a mutablechar[]where each index can be updated directly before callingnew String(chars).isPalindromechecks mirror characters directly onsusings.charAt(...)in O(n) time and O(1) extra space.
When the output string has the exact same length as the input string (for example, reversing a string, swapping vowels, shifting characters in a cipher, or toggling case), a char[] array is even simpler than StringBuilder:
- Call
char[] chars = s.toCharArray();(O(n) time and space). - Read and write
chars[i]directly with array indexing (chars[i] = ...). - Convert back once at the end with
new String(chars)(O(n) time). - Use
StringBuilderwhen the output length grows or shrinks dynamically (filtering characters, run-length encoding, joining tokens). - Use
char[](s.toCharArray()→ mutate →new String(chars)) when the length is fixed and you want index-based swaps or overwrites.
Fix the error
Fix the compile error
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
The loop should print every letter of the char array.
Error
FlipDemo.java:4: error: cannot find symbol
for (int i = 0; i < letters.length(); i++) {
symbol: method length()
location: variable letters of type char[]Palindrome checks: allocating a reversed copy vs two pointers
A palindrome reads the same forwards and backwards. You can check it with a reversed copy or with two pointers that need no extra memory. The code below compares both.
public class PalindromeCheck { public static void main(String[] args) { String s = "racecar"; System.out.println(new StringBuilder(s).reverse().equals(s)); // StringBuilder vs String System.out.println(new StringBuilder(s).reverse().toString().equals(s)); // O(n) extra copy boolean same = true; for (int left = 0, right = s.length() - 1; left < right; left++, right--) { if (s.charAt(left) != s.charAt(right)) { same = false; // O(1) extra space: two int pointers break; } } System.out.println(same); }}false true true
A palindrome is a string that reads the same forwards and backwards (such as "racecar" or "noon"). There are two ways to check if s is a palindrome:
- StringBuilder reverse (O(n) time, O(n) extra space):
s.equals(new StringBuilder(s).reverse().toString()). Short to write, but allocates a copy of the string. - Two-pointer scan (O(n) time, O(1) extra space): Compare
s.charAt(left)ands.charAt(right)whileleft < right, steppingleft++andright--. No extra string or array is allocated at all!
new StringBuilder(s).reverse().equals(s) — StringBuilder does not override Object.equals(), and a StringBuilder is never .equals() to a String! Always call .toString() before .equals(s), or use the O(1)-space two-pointer loop.Next step
Check your understanding
10 quick questions