HuntExams Academy logo
JavaBeginner#strings

What is the difference between String, StringBuilder, and StringBuffer?

Answer

String is immutable. StringBuilder is mutable and not thread-safe (fast). StringBuffer is mutable and synchronized (thread-safe, slower). Use StringBuilder for single-threaded concatenation in loops.

Example

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i);
System.out.println(sb.toString()); // "01234"

Detailed explanation

String, StringBuilder, and StringBuffer all represent character sequences in Java, but they differ in mutability and synchronization. String is immutable: once created, its contents cannot change. Methods such as concat(), replace(), and toUpperCase() do not modify the original instance; they return a result, which may be the same instance when no change is needed. For example, s = s + "x" changes the reference stored in s rather than modifying the original String. Immutability makes String suitable for map keys and safely sharing text between threads.

StringBuilder is mutable and is intended for constructing or editing text. Operations such as append(), insert(), and delete() modify the builder's contents. Internally, it maintains expandable storage with a capacity that can exceed its current length. When that storage fills up, a larger allocation and copying may be required. Reusing this storage avoids repeatedly creating intermediate strings during incremental construction. For example, StringBuilder sb = new StringBuilder(); followed by for (int i = 0; i < 5; i++) sb.append(i); produces "01234" when sb.toString() is called. The returned String remains unchanged if the builder is subsequently modified.

StringBuffer offers similar mutable operations, but its methods synchronize access to the instance where necessary. This protects individual operations when multiple threads use the same buffer. However, a sequence such as checking length and then appending is not automatically atomic; another thread can act between those calls. StringBuilder does not provide this synchronization and should normally stay confined to one thread. StringBuffer's synchronization can add overhead, so StringBuilder is generally preferred when shared access is unnecessary, although actual performance depends on the workload and JVM optimizations.

In interviews, explain the trade-off rather than simply ranking the classes by speed. Use String for ordinary text values, StringBuilder for repeated concatenation or editing within one thread, and StringBuffer when a shared mutable buffer needs synchronized operations. Avoid claiming that every use of + is inefficient: constant expressions can be folded, and modern Java can optimize concatenation expressions. Repeatedly extending a String inside a loop can still cause substantial allocation and copying, making a builder the clearer practical choice.

Key points to remember

  • String is immutable; reassignment changes a reference, not the original object's contents.
  • StringBuilder is mutable and provides no built-in synchronization.
  • StringBuffer is mutable and synchronizes operations, but compound actions may need additional locking.
  • Prefer StringBuilder for repeated text construction in a single thread.
  • Builders have a length and a capacity; toString() produces an immutable String.

Common mistakes candidates make

  • Claiming that a final StringBuilder is immutable; final prevents reassignment, not content changes.
  • Assuming StringBuffer makes every multi-step operation automatically atomic.
  • Saying StringBuilder is always faster or that every String concatenation must be replaced with a builder.

Likely follow-up questions

What is the difference between a builder's length and capacity?

Length is the number of characters currently stored, while capacity is the available character storage before expansion is needed. Providing an estimated initial capacity can reduce resizing when the expected output size is known.

Do StringBuilder and StringBuffer compare contents with equals()?

Neither overrides Object.equals(), so distinct instances are not equal even when their contents match. To compare text, convert them to strings and use String.equals(), or use String.contentEquals() against a character sequence.

Can StringBuilder be used in a multithreaded application?

Yes, if each builder is confined to one thread or access is coordinated through appropriate external synchronization. A multithreaded application does not require StringBuffer for builders used only as local, unshared objects.

Interview tip: Start with mutability and synchronization, then demonstrate the loop example and explain why StringBuilder fits that use case.

Related Interview Questions

1
JavaIntermediate#strings

Why are Strings immutable in Java?

Open
2
JavaIntermediate#collections

Explain the Collections framework hierarchy.

Open
3
JavaBeginner#collections#list

ArrayList vs LinkedList?

Open