StringBuilder
StringBuilder is a mutable class in Java used to create and modify strings efficiently. It is designed for high-performance string manipulation in single-threaded scenarios and is one of the most commonly used alternatives to String. This is a very common interview topic, especially in comparison with String and StringBuffer.
What Is StringBuilder?
- A mutable sequence of characters
- Part of the java.lang package
- Not thread-safe (no synchronization)
- Faster than String and StringBuffer
StringBuilder sb = new StringBuilder("Java");
Why StringBuilder Exists
- String → Immutable (creates new objects on modification)
- StringBuffer → Thread-safe but slower
- StringBuilder → Fast and mutable (no synchronization overhead)
Best use case: Single-threaded applications with frequent string modifications.
Key Characteristics of StringBuilder
- Mutable (content can change)
- Not synchronized (not thread-safe)
- High performance
- Same API as StringBuffer
How StringBuilder Works (Conceptual)
StringBuilder sb = new StringBuilder("Java");
sb.append(" World");
• Same object is modified
• No new object created
• Memory-efficient for repeated changes
Constructors of StringBuilder
StringBuilder sb1 = new StringBuilder(); // capacity = 16
StringBuilder sb2 = new StringBuilder("Java"); // 16 + length
StringBuilder sb3 = new StringBuilder(50); // custom capacity
Capacity Concept (Important for Interviews)
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity()); // 16
Capacity Growth Formula
newCapacity = (oldCapacity * 2) + 2
Commonly Used StringBuilder Methods
append()
sb.append(" Java");
sb.append(8);
sb.append(true);
insert()
sb.insert(4, " Core");
replace()
sb.replace(0, 4, "Core");
delete() / deleteCharAt()
sb.delete(0, 4);
sb.deleteCharAt(2);
reverse()
sb.reverse();
length() and capacity()
sb.length();
sb.capacity();
Example Program
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
sb.insert(4, " Core");
sb.replace(0, 4, "Core");
sb.delete(0, 5);
System.out.println(sb);
String Concatenation vs StringBuilder (Performance)
Using String (Inefficient)
String s = "";
for (int i = 0; i < 1000; i++) {
s = s + i;
}
• Creates many temporary objects
• Poor performance
Using StringBuilder (Efficient)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
• Single object
• Much faster
StringBuilder vs StringBuffer vs String
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread Safety | Yes | No | Yes |
| Synchronization | N/A | No | Yes |
| Performance | Slow | Fastest | Slower |
| Use Case | Read-only | Single-thread | Multi-thread |
When to Use StringBuilder
- Frequent string modifications
- Single-threaded applications
- Performance-critical code
- Loops and string concatenation
When NOT to Use StringBuilder
- Multi-threaded shared access
- When immutability is required
- When thread safety is mandatory
Common Beginner Mistakes
- Using StringBuilder in multi-threaded code
- Assuming it is thread-safe
- Forgetting capacity planning
- Using String concatenation in loops
Interview-Ready Answers
Short Answer
StringBuilder is a mutable, non-thread-safe class used for fast string manipulation.
Detailed Answer
In Java, StringBuilder allows modification of string content without creating new objects. It is not synchronized, making it faster than StringBuffer, and is ideal for single-threaded applications where performance is critical.
StringBuilder Examples
1. Creating a StringBuilder Object
StringBuilder sb = new StringBuilder("Java");
Explanation
- Creates a mutable sequence of characters.
- Stored in heap memory.
- Not thread-safe (faster than StringBuffer).
2. Default StringBuilder Constructor
StringBuilder sb = new StringBuilder();
System.out.println(sb.length());
Explanation
- Empty builder.
- Initial length = 0.
- Default capacity = 16.
3. StringBuilder with Initial Capacity
StringBuilder sb = new StringBuilder(50);
System.out.println(sb.capacity());
Explanation
- Reserves memory in advance.
- Improves performance when size is known.
4. Appending Text (append())
StringBuilder sb = new StringBuilder("Java");
sb.append(" Selenium");
System.out.println(sb);
Explanation
- Modifies the same object.
- No new object creation.
- Output: Java Selenium.
5. Appending Different Data Types
StringBuilder sb = new StringBuilder("Count: ");
sb.append(10);
sb.append(true);
sb.append(5.5);
System.out.println(sb);
Explanation
- Supports multiple data types.
- Output: Count: 10true5.5.
6. Inserting Text (insert())
StringBuilder sb = new StringBuilder("Java");
sb.insert(4, " Selenium");
System.out.println(sb);
Explanation
- Inserts at specified index.
- Output: Java Selenium.
7. Deleting Characters (delete())
StringBuilder sb = new StringBuilder("Java Selenium");
sb.delete(4, 13);
System.out.println(sb);
Explanation
- Deletes substring between indices.
- Output: Java.
8. Deleting Single Character (deleteCharAt())
StringBuilder sb = new StringBuilder("Javva");
sb.deleteCharAt(3);
System.out.println(sb);
Explanation
- Removes character at index.
- Output: Java.
9. Reversing Text (reverse())
StringBuilder sb = new StringBuilder("Java");
sb.reverse();
System.out.println(sb);
Explanation
- Reverses characters in place.
- Output: avaJ.
10. Replacing Substring (replace())
StringBuilder sb = new StringBuilder("Java Automation");
sb.replace(5, 15, "Selenium");
System.out.println(sb);
Explanation
- Replaces characters between indices.
- Output: Java Selenium.
11. Finding Length
StringBuilder sb = new StringBuilder("Java");
System.out.println(sb.length());
Explanation
- Returns number of characters.
- Output: 4.
12. Finding Capacity
StringBuilder sb = new StringBuilder("Java");
System.out.println(sb.capacity());
Explanation
- Capacity = 16 + initial string length.
- Output: 20.
13. Ensuring Capacity (ensureCapacity())
StringBuilder sb = new StringBuilder();
sb.ensureCapacity(40);
System.out.println(sb.capacity());
Explanation
- Ensures minimum capacity.
- Reduces resizing cost.
14. Character Access (charAt())
StringBuilder sb = new StringBuilder("Java");
System.out.println(sb.charAt(1));
Explanation
- Accesses character by index.
- Output: a.
15. Setting Character (setCharAt())
StringBuilder sb = new StringBuilder("Java");
sb.setCharAt(1, 'o');
System.out.println(sb);
Explanation
- Modifies character at index.
- Output: Jova.
16. Converting StringBuilder to String
StringBuilder sb = new StringBuilder("Java");
String s = sb.toString();
System.out.println(s);
Explanation
- Creates immutable String.
- Used when returning values.
17. String vs StringBuilder Performance Example
String s = "";
for (int i = 1; i <= 5; i++) {
s = s + i;
}
System.out.println(s);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
}
System.out.println(sb);
Explanation
- String creates multiple objects.
- StringBuilder uses single object.
- Preferred in loops.
18. Using StringBuilder in Loops (Best Practice)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("Test ");
}
System.out.println(sb);
Explanation
- Efficient concatenation.
- Common real-world use.
19. Comparing StringBuilder Objects
StringBuilder sb1 = new StringBuilder("Java");
StringBuilder sb2 = new StringBuilder("Java");
System.out.println(sb1.equals(sb2));
Explanation
- equals() not overridden.
- Compares references.
- Output: false.
20. Correct Way to Compare StringBuilder Content
StringBuilder sb1 = new StringBuilder("Java");
StringBuilder sb2 = new StringBuilder("Java");
System.out.println(sb1.toString().equals(sb2.toString()));
Explanation
- Convert to String.
- Output: true.
21. Clearing a StringBuilder
StringBuilder sb = new StringBuilder("Java");
sb.setLength(0);
System.out.println(sb.length());
Explanation
- Clears content.
- Output: 0.
22. StringBuilder Substring
StringBuilder sb = new StringBuilder("Automation");
String sub = sb.substring(0, 4);
System.out.println(sub);
Explanation
- Returns a String, not StringBuilder.
- Output: Auto.
23. StringBuilder with Null Handling
StringBuilder sb = new StringBuilder();
sb.append((String) null);
System.out.println(sb);
Explanation
- Appends literal "null".
- Output: null.
24. Thread Safety Difference (Conceptual)
StringBuilder sb = new StringBuilder("Fast");
sb.append(" Unsafe");
Explanation
- Not synchronized.
- Faster than StringBuffer.
- Not safe in multi-threaded environments.
25. Interview Summary Example (StringBuilder)
StringBuilder sb = new StringBuilder("Java");
sb.append(" Builder");
System.out.println(sb);
Explanation
- Demonstrates:
- Mutability.
- Performance advantage.
- Heap storage.
- Very common interview discussion topic.
Key Takeaway
Use StringBuilder for fast, mutable string operations in single-threaded scenarios. Avoid it when thread safety or immutability is required.