Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javaeasy

String vs StringBuilder vs StringBuffer — when to use which?

Tags
#string#stringbuilder#performance
Back to categoryPractice quiz

Answer

`String` is immutable, so repeated concatenation creates many objects. `StringBuilder` is mutable and fast for building strings in a single thread; `StringBuffer` is similar but synchronized (rarely needed today).

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
  sb.append(i).append(",");
}
System.out.println(sb.toString());

Advanced answer

Deep dive

  • `String` is immutable: concatenation creates new objects.
  • `StringBuilder` is mutable and not synchronized: fastest for building strings in a single thread (or when the builder is not shared).
  • `StringBuffer` is like `StringBuilder` but synchronized: safer if one instance is shared across threads, but slower.

Practical guidance

  • Use `String` for fixed literals and small, non-loop concatenations.
  • Use `StringBuilder` in loops and when building large strings.
  • Prefer `StringBuilder` over `StringBuffer` unless you truly share the same instance across threads.

Example

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i).append(",");
String out = sb.toString();

Common pitfalls

  • `s += x` in a loop (many temporary Strings).
  • Assuming `StringBuilder` is thread-safe.
  • Not sizing builders when you know approximate length (`new StringBuilder(capacity)`).

Related questions

Java
JIT compilation: what is it and why do Java apps “warm up”?
#java#jit#performance
Java
Generational garbage collection: why does the JVM split memory into young/old?
#java#gc#jvm
Java
StringBuilder vs StringBuffer: what’s the difference?
#java
#string
#performance
Java
Parallel streams: when can they help and what are common pitfalls?
#java#streams#parallel
Java
In Java, what’s the difference between `==` and `.equals()`?
#equals#reference#string
Java
Why is String immutable in Java?
#string#immutability#memory