Java Notes
Complete guide to StringBuilder in Java covering mutable string operations, performance benefits, method chaining, capacity management, and comparison with String and StringBuffer.
What is StringBuilder?
StringBuilder is a mutable, non-synchronized class for building and modifying character sequences. Introduced in Java 5 (JDK 1.5), it was created as a faster alternative to StringBuffer for single-threaded scenarios.
StringBuilder has the exact same API as StringBuffer (same methods, same behavior) but without the synchronized keyword on methods. This eliminates locking overhead, making it significantly faster.
Key Facts
| Feature | StringBuilder |
|---|---|
| Mutability | Mutable — content changed in-place |
| Thread Safety | NOT thread-safe — no synchronization |
| Performance | Fastest for string modification |
| Package | java.lang (auto-imported) |
| Since | Java 5 (JDK 1.5) |
| Implements | CharSequence, Appendable, Serializable |
| Default Capacity | 16 characters |
When to Use StringBuilder
Use StringBuilder when:
- You need to modify a string multiple times (especially in loops)
- You're working in a single-threaded context (most common case)
- Performance matters more than thread-safety
Don't use when:
- Multiple threads access the same builder → use StringBuffer
- The string doesn't change → use String
Why StringBuilder Exists
Before Java 5, the only mutable string option was StringBuffer (synchronized). But synchronization has overhead even when only one thread is involved:
StringBuffer: 45 ms StringBuilder: 28 ms StringBuilder is ~1.6x faster
Constructors
public class Constructors {
public static void main(String[] args) {
// 1. Default: empty, capacity 16
StringBuilder sb1 = new StringBuilder();
System.out.println("Default - length: " + sb1.length() + ", capacity: " + sb1.capacity());
// 2. With capacity
StringBuilder sb2 = new StringBuilder(100);
System.out.println("Capacity(100) - length: " + sb2.length() + ", capacity: " + sb2.capacity());
// 3. With initial string (capacity = str.length() + 16)
StringBuilder sb3 = new StringBuilder("Hello");
System.out.println("String(\"Hello\") - length: " + sb3.length() + ", capacity: " + sb3.capacity());
// 4. With CharSequence
CharSequence cs = "World";
StringBuilder sb4 = new StringBuilder(cs);
System.out.println("CharSequence - length: " + sb4.length() + ", capacity: " + sb4.capacity());
}
}Default - length: 0, capacity: 16
Capacity(100) - length: 0, capacity: 100
String("Hello") - length: 5, capacity: 21
CharSequence - length: 5, capacity: 21Core Methods
append() — The Workhorse
append() is overloaded for every data type. It adds content to the end and returns this for chaining.
public class AppendExamples {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
// Append different types
sb.append("Name: "); // String
sb.append("Alice"); // String
sb.append("\nAge: "); // String with newline
sb.append(25); // int
sb.append("\nGPA: "); // String
sb.append(3.85); // double
sb.append("\nActive: "); // String
sb.append(true); // boolean
System.out.println(sb);
// Method chaining — cleaner syntax
StringBuilder profile = new StringBuilder()
.append("=== Student Profile ===\n")
.append("ID: ").append(1001).append("\n")
.append("Name: ").append("Bob").append("\n")
.append("Grade: ").append('A');
System.out.println("\n" + profile);
}
}Name: Alice Age: 25 GPA: 3.85 Active: true === Student Profile === ID: 1001 Name: Bob Grade: A
insert() — Add at Position
public class InsertExamples {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World!");
System.out.println("Original: " + sb);
// Insert at beginning
sb.insert(0, ">>> ");
System.out.println("Insert at 0: " + sb);
// Insert in middle
sb.insert(9, "Beautiful ");
System.out.println("Insert at 9: " + sb);
// Insert at end
sb.insert(sb.length(), " <<<");
System.out.println("Insert at end: " + sb);
// Insert different types
StringBuilder sb2 = new StringBuilder("Value: ");
sb2.insert(7, 42);
System.out.println("Insert int: " + sb2);
}
}Original: Hello World! Insert at 0: >>> Hello World! Insert at 9: >>> Hello Beautiful World! Insert at end: >>> Hello Beautiful World! <<< Insert int: Value: 42
delete() and deleteCharAt()
public class DeleteExamples {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello Beautiful World");
System.out.println("Original: " + sb);
// delete(startIndex, endIndex) — endIndex exclusive
sb.delete(5, 15);
System.out.println("delete(5,15): " + sb);
// deleteCharAt(index)
sb.deleteCharAt(sb.length() - 1); // Remove last char
System.out.println("deleteCharAt last: " + sb);
// Clear entire StringBuilder
sb.delete(0, sb.length());
System.out.println("Cleared: \"" + sb + "\" (length=" + sb.length() + ")");
// Alternative: sb.setLength(0) also clears it
}
}Original: Hello Beautiful World delete(5,15): Hello World deleteCharAt last: Hello Worl Cleared: "" (length=0)
replace()
public class ReplaceExamples {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
System.out.println("Original: " + sb);
// replace(start, end, newString)
sb.replace(6, 11, "Java");
System.out.println("replace(6,11,\"Java\"): " + sb);
// Replacement can be longer or shorter
sb.replace(0, 5, "Welcome to");
System.out.println("replace(0,5,\"Welcome to\"): " + sb);
}
}Original: Hello World replace(6,11,"Java"): Hello Java replace(0,5,"Welcome to"): Welcome to Java
reverse()
public class ReverseExamples {
public static void main(String[] args) {
// Basic reverse
StringBuilder sb = new StringBuilder("Hello");
sb.reverse();
System.out.println("Reversed: " + sb);
// Palindrome check
String[] words = {"madam", "hello", "racecar", "java", "level"};
for (String word : words) {
String reversed = new StringBuilder(word).reverse().toString();
System.out.println(word + " → palindrome: " + word.equals(reversed));
}
}
}Reversed: olleH madam → palindrome: true hello → palindrome: false racecar → palindrome: true java → palindrome: false level → palindrome: true
charAt(), setCharAt(), indexOf()
public class AccessMethods {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
// charAt
System.out.println("charAt(0): " + sb.charAt(0));
System.out.println("charAt(6): " + sb.charAt(6));
// setCharAt — modifies character in place
sb.setCharAt(0, 'h');
sb.setCharAt(6, 'w');
System.out.println("After setCharAt: " + sb);
// indexOf
sb = new StringBuilder("Java is great and Java is fun");
System.out.println("indexOf(\"Java\"): " + sb.indexOf("Java"));
System.out.println("indexOf(\"Java\", 5): " + sb.indexOf("Java", 5));
System.out.println("lastIndexOf(\"Java\"): " + sb.lastIndexOf("Java"));
}
}charAt(0): H
charAt(6): W
After setCharAt: hello world
indexOf("Java"): 0
indexOf("Java", 5): 18
lastIndexOf("Java"): 18Practical Use Cases
Use Case 1: Building HTML
public class HtmlBuilder {
public static void main(String[] args) {
String[] items = {"Apple", "Banana", "Cherry"};
StringBuilder html = new StringBuilder();
html.append("<ul>\n");
for (String item : items) {
html.append(" <li>").append(item).append("</li>\n");
}
html.append("</ul>");
System.out.println(html);
}
}<ul> <li>Apple</li> <li>Banana</li> <li>Cherry</li> </ul>
Use Case 2: Building CSV
Name,Age,Role Alice,25,Engineer Bob,30,Designer Charlie,28,Manager
Use Case 3: String Manipulation Algorithm
public class RemoveVowels {
public static void main(String[] args) {
String input = "Hello World Java Programming";
StringBuilder result = new StringBuilder();
for (char c : input.toCharArray()) {
if ("aeiouAEIOU".indexOf(c) == -1) {
result.append(c);
}
}
System.out.println("Original: " + input);
System.out.println("Without vowels: " + result);
}
}Original: Hello World Java Programming Without vowels: Hll Wrld Jv Prgrmmng
Java Compiler and StringBuilder
The Java compiler automatically uses StringBuilder for string concatenation with the + operator:
// What you write:
String result = "Hello" + " " + name + "!";
// What the compiler generates (approximately):
String result = new StringBuilder()
.append("Hello")
.append(" ")
.append(name)
.append("!")
.toString();However, in a loop, each iteration creates a NEW StringBuilder:
StringBuilder vs StringBuffer — Summary
public class ComparisonTable {
public static void main(String[] args) {
System.out.println("Feature | StringBuilder | StringBuffer");
System.out.println("----------------|--------------------|-----------------");
System.out.println("Mutability | Mutable | Mutable");
System.out.println("Thread-safe | No | Yes (synchronized)");
System.out.println("Performance | Faster | Slower");
System.out.println("Since | Java 5 | Java 1.0");
System.out.println("Use when | Single-threaded | Multi-threaded");
System.out.println("API | Same methods | Same methods");
// Demonstrate identical API
StringBuilder sb = new StringBuilder("Test");
StringBuffer sbf = new StringBuffer("Test");
sb.append("!").reverse();
sbf.append("!").reverse();
System.out.println("\nStringBuilder result: " + sb);
System.out.println("StringBuffer result: " + sbf);
}
}Feature | StringBuilder | StringBuffer ----------------|--------------------|----------------- Mutability | Mutable | Mutable Thread-safe | No | Yes (synchronized) Performance | Faster | Slower Since | Java 5 | Java 1.0 Use when | Single-threaded | Multi-threaded API | Same methods | Same methods StringBuilder result: !tseT StringBuffer result: !tseT
Capacity Management Best Practice
Both produce same result: true Pre-allocation avoids multiple array copies!
Common Mistakes
- Using StringBuilder for single concatenation —
"Hello" + nameis fine without StringBuilder - Not using StringBuilder in loops — the most common performance mistake
- Sharing StringBuilder between threads — not thread-safe, use StringBuffer
- Forgetting that methods modify in-place —
sb.reverse()changessbitself - Calling toString() multiple times — creates new String each time, cache if needed
- Not setting initial capacity for known large strings — causes multiple resize operations
Best Practices
- Use StringBuilder by default for mutable strings (most code is single-threaded)
- Set initial capacity when you know approximate size
- Use method chaining for readability
- Convert to String only once at the end with
toString() - Use setLength(0) to reuse instead of creating new StringBuilder
- Don't use StringBuilder for simple concatenation —
a + bis fine - Use in loops where you're building strings iteratively
- Prefer StringBuilder over StringBuffer unless multi-threaded access is proven necessary
Interview Questions
Q1: What is StringBuilder? A mutable, non-synchronized class for building strings efficiently in single-threaded contexts. Introduced in Java 5.
Q2: StringBuilder vs StringBuffer? Same API, same functionality. StringBuilder is faster (no synchronization). StringBuffer is thread-safe. Use StringBuilder by default.
Q3: When does the compiler use StringBuilder? For + operator string concatenation. But NOT optimally in loops — manual StringBuilder is needed there.
Q4: What is the default capacity? 16 characters. Pre-allocate with constructor if you know the approximate size.
Q5: How does capacity grow? New capacity = (current × 2) + 2. If still insufficient, grows to required size.
Q6: Is StringBuilder final? No, unlike String. But it's rarely subclassed in practice.
Q7: Does StringBuilder override equals()? No. Use sb1.toString().equals(sb2.toString()) for content comparison.
Q8: Can StringBuilder be null? The reference can be null, but the internal buffer always exists once constructed.
Q9: How to clear a StringBuilder? sb.setLength(0) or sb.delete(0, sb.length()). setLength is slightly faster.
Q10: Why not always use StringBuilder instead of String? Strings are immutable — safe for sharing, good as HashMap keys, thread-safe. StringBuilder is only better when you need frequent modification.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for StringBuilder in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, strings, stringbuilder
Related Java Master Course Topics