What is the difference between String and StringBuilder?
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.
- String is immutable, so every change creates a new object.
- StringBuilder is mutable and edits the same object, which is far faster for many changes.
- Use String for fixed text and StringBuilder for building or looping string changes.
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.
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.
Frequently asked questions
What is the difference between StringBuilder and StringBuffer?
Both are mutable, but StringBuffer is synchronised and thread safe while StringBuilder is not. StringBuilder is faster in single threaded code.
Why is String immutable in Java?
Immutability makes strings safe to share, allows caching in the string pool, and lets them be used safely as keys and in multithreaded code.
Common follow up questions
Related interview questions
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