Java Interview Question

What is the difference between String and StringBuilder?

Updated 2026-07-10 · Beginner friendly
Quick answer

A String in Java is immutable, so every change actually creates a new String object, which is wasteful in loops. StringBuilder is mutable, so it changes the same object in place, which is far faster when you build text step by step. Use String for fixed text and StringBuilder when you concatenate a lot, such as inside a loop.

Why String is immutable

Once created, a String cannot change. Appending to it makes a brand new object and leaves the old one for garbage collection. Immutability makes Strings safe to share, but it wastes memory when you modify text repeatedly.

// Slow: creates many temporary String objects
String r = "";
for (int i = 0; i < 1000; i++) r += i;

// Fast: one object modified in place
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append(i);
String result = sb.toString();

What about StringBuffer

StringBuffer is like StringBuilder but thread safe, because its methods are synchronised. That safety makes it slightly slower, so prefer StringBuilder unless multiple threads share the same buffer.

In the interview

The winning line is String is immutable, StringBuilder is mutable and faster for repeated changes. Adding that StringBuffer is the thread safe version of StringBuilder answers the usual follow up before it is asked.

Want the full Java guide?

Read every Java concept with notes, diagrams, and code in one place. Track your progress as you go.

Open the Java guide All Java questions