Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

String is a printed certificate — you can't edit it. StringBuilder is a whiteboard — you write, erase, rewrite on the SAME surface. No new board needed every time.

The Problem StringBuilder Solves

java
QUBITS OF DPK
1// ❌ BAD — String concatenation in loop
2String result = "";
3for (int i = 0; i < 10000; i++) {
4    result = result + i;   // 10,000 new objects!
5}
6
7// ✅ GOOD — StringBuilder
8StringBuilder result = new StringBuilder();
9for (int i = 0; i < 10000; i++) {
10    result.append(i);      // same object modified
11}
12String final = result.toString();
Performance:
javascript
QUBITS OF DPK
1String:        ~350ms
2StringBuilder: ~2ms

StringBuilder Methods

java
QUBITS OF DPK
1StringBuilder sb = new StringBuilder("Hello");
2
3sb.append(" Deepak");    // Hello Deepak
4sb.insert(5, ",");       // Hello, Deepak
5sb.delete(5, 6);         // Hello Deepak
6sb.replace(6, 12, "World"); // Hello World
7sb.reverse();            // dlroW olleH
8sb.length();             // 11
9sb.charAt(0);            // 'd'
10sb.toString();           // convert back to String — MANDATORY!

Comparison Table

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — Must reassign String modifications
2name.concat(" Kumar");   // ❌ result lost
3name = name.concat(" Kumar");  // ✅
4
5// Trap 2 — toString() mandatory
6StringBuilder sb = new StringBuilder("Hi");
7String s = sb;            // ❌ compile error
8String s = sb.toString(); // ✅
9
10// Trap 3 — StringBuilder not thread safe
11// In multithreaded code → use StringBuffer
12
13// Trap 4 — new String() vs literal
14String a = "Hi";
15String b = new String("Hi");
16a == b   // false!
17a.equals(b)  // true

Production Use Cases

java
QUBITS OF DPK
1// Building SQL queries dynamically
2StringBuilder query = new StringBuilder();
3query.append("SELECT * FROM users");
4query.append(" WHERE age > 18");
5query.append(" ORDER BY name");
6String sql = query.toString();
7
8// Building JSON strings
9// Building log messages in loops
10// Building CSV data

Interview Answer (SDE-2)

"StringBuilder provides a mutable character sequence that modifies the same object — solving String's performance problem in loops. String concatenation in a loop creates a new object per iteration; StringBuilder appends in-place giving dramatically better performance. StringBuilder is not thread-safe — for multithreaded scenarios use StringBuffer which synchronizes methods. Key methods: append, insert, delete, reverse, replace, toString. Always call toString() to convert back to String."

Interview Questions & MAANG-Level Answers

Q1. What is the difference between String, StringBuilder, and StringBuffer?
String is immutable — every modification creates a new object, thread-safe by nature, stored in String Pool. StringBuilder is mutable — modifies same object, NOT thread-safe, fast — use in single-threaded code. StringBuffer is mutable — modifies same object, thread-safe (synchronized methods), slightly slower — use in multi-threaded code. In practice: String for fixed text, StringBuilder for 99% of string building, StringBuffer only when sharing across threads.
Q2. Why is StringBuilder faster than String for concatenation?
StringBuilder maintains an internal resizable char[]. append() adds characters to this array in-place. When capacity is exceeded, array is doubled. No new objects created per operation. String concatenation creates a new String object every time (immutability), abandoning the old one for GC. For n concatenations: String is O(n²) total work, StringBuilder is O(n) amortized.
Q3. When would you use StringBuffer over StringBuilder?
Only when multiple threads access and modify the same string builder concurrently. StringBuffer methods are synchronized — only one thread can execute at a time. In modern Java, this scenario is rare since you'd typically design thread-local string operations. In practice, StringBuilder is used 99% of the time. If thread safety is needed at a higher level, you'd usually use other synchronization mechanisms rather than StringBuffer.
Q4. What happens if you do String s = sb where sb is StringBuilder?
Compile error: Type mismatch: cannot convert from StringBuilder to String. StringBuilder and String are completely different types with no implicit conversion. You must explicitly call sb.toString() to convert: String s = sb.toString(). This is a frequent trap for beginners who forget toString().
Q5. What is the time complexity difference between String loop concatenation and StringBuilder?
String concatenation in loop: O(n²) — each + creates a new string of increasing length, copying all previous characters. For n iterations with final string of length n: 1+2+3...+n = n(n+1)/2 = O(n²) total character copies. StringBuilder: O(n) amortized — append is O(1) amortized (array doubling when capacity exceeded). For 1MB string, String loop might take minutes; StringBuilder takes milliseconds.