StringBuilder in Java
StringBuilder is the single-threaded counterpart to StringBuffer. Introduced in Java 5, it provides exactly the same API—append, insert, delete, replace,...
Fast String Manipulation with StringBuilder
StringBuilder is the single-threaded counterpart to StringBuffer. Introduced in Java 5, it provides exactly the same API—append, insert, delete, replace, reverse, and toString—but without the synchronization overhead. Because it does not acquire locks, StringBuilder is significantly faster than StringBuffer in single-threaded contexts, which covers the vast majority of string-building scenarios in typical applications.
Why Immutability Makes StringBuilder Necessary Every time you use the + operator to concatenate strings in a loop, Java creates a new String object for every iteration. If you concatenate one thousand strings this way, you create one thousand intermediate objects, most of which immediately become garbage. StringBuilder avoids this entirely: all modifications happen in place on the same char array, and you call toString() only once at the end to produce the final String.
Method API in Detail The append method is overloaded to accept every Java type: int, long, double, boolean, char, char[], String, and Object. This means you can append a mix of values without explicit casting or conversion. The charAt(index) and setCharAt(index, ch) methods let you read and update individual characters. length() returns the current content length, while capacity() returns the allocated array size, which is always at least as large as the length.
When to Choose StringBuilder Use StringBuilder when you build a string inside a loop, format complex output from many parts, or implement algorithms that manipulate text character by character such as palindrome checks or anagram generation. In Java 9 and later, the compiler automatically rewrites simple + concatenation using invokedynamic instructions, but explicit StringBuilder is still clearer and more predictable for complex multi-statement building.
Code Example: StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 5; i++) { sb.append(i); if (i < 5) sb.append(", "); } System.out.println(sb.toString()); // 1, 2, 3, 4, 5
Interview Tip: A frequent interview task is to reverse a string without using any library reverse method. The clean solution is: new StringBuilder(input).reverse().toString(). This demonstrates knowledge of StringBuilder's API and avoids manually swapping characters. Follow up by explaining why this is O(n) time and O(n) space.