The short answer

String is immutable, so every change makes a new object, which is simple and thread-safe but slow for heavy edits. StringBuilder is mutable and edits one buffer in place, so it is fast, but it is not thread-safe. StringBuffer is the same as StringBuilder yet synchronised, so it is thread-safe but a little slower. In short, use String for fixed text, StringBuilder for fast single-threaded building, and StringBuffer when many threads share the buffer.

String, StringBuilder, and StringBuffer are the three ways Java holds and builds text. All three appear in every Java and interview syllabus. Beginners often blur which one is mutable and which one is thread-safe, so choosing the wrong one hurts performance.

The core split is mutability and thread safety. Can the object change in place, and is it safe across threads? String says no to both, StringBuilder says yes then no, and StringBuffer says yes to both. This guide defines each class, shows the code, compares them in detail, and explains when to use which.

If you are still mapping out Java basics, it also helps to know the difference between checked and unchecked exceptions.

Three panels comparing String as immutable and thread-safe, StringBuilder as mutable and fast, and StringBuffer as mutable and synchronized
String is immutable; StringBuilder is mutable and fast; StringBuffer is mutable and synchronized.

What is String?

The String class represents a sequence of characters. Once created, a String is immutable, so its value cannot change. Any operation that seems to modify a String actually creates a new String object, and the old one is left untouched.

Because of that, Java can keep string literals in a shared string pool, so equal literals reuse one object. Immutability also makes String naturally thread-safe. The cost shows up only when you change text often, since each change allocates a new object.

Advantages of String:

  • Simple to use and understand.
  • Thread-safe, because it is immutable.
  • Literals are cached in the string pool, which saves memory.

Disadvantages of String:

  • Inefficient for frequent changes, since each one creates a new object.
  • Repeated concatenation in a loop wastes memory and time.

What is StringBuilder?

The StringBuilder class is like String but mutable, so it changes text without creating new objects. It provides methods to append, insert, delete, and replace characters in one internal buffer. Therefore it suits building or editing text quickly.

StringBuilder is not synchronised, so it does no thread-safety locking. As a result, it is the fastest of the three for string building, which makes it the default choice in single-threaded code.

Advantages of StringBuilder:

  • Efficient for frequent modifications, since it edits in place.
  • Not synchronised, so it is faster than StringBuffer.
  • Rich methods for append, insert, delete, and reverse.

Disadvantages of StringBuilder:

  • Not thread-safe, so two threads can corrupt the buffer.
  • Needs a final toString() call to get a String back.

What is StringBuffer?

The StringBuffer class is like StringBuilder but synchronised, which makes it thread-safe. Its methods are marked synchronized, so only one thread can change the buffer at a time. Hence it fits cases where several threads share the same buffer.

That locking has a price. Because each method acquires a lock, StringBuffer runs a little slower than StringBuilder. So you pay for safety only when you actually need it.

Advantages of StringBuffer:

  • Thread-safe, because its methods are synchronised.
  • Mutable, so it edits text without new objects.
  • Safe for many threads sharing one buffer.

Disadvantages of StringBuffer:

  • Slower than StringBuilder, due to synchronisation overhead.
  • Unnecessary in single-threaded code, where the lock adds no value.

String vs StringBuilder vs StringBuffer: Comparison Table

Grid with three columns for String, StringBuilder and StringBuffer comparing mutable no/yes/yes, thread-safe yes/no/yes, and speed slow/fast/medium
The three classes at a glance: mutable, thread-safe, and speed.
AspectStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread safetyThread-safe (immutable)Not thread-safeThread-safe (synchronised)
SynchronisationNot applicableNot synchronisedSynchronised methods
ConcatenationCreates a new object each timeEfficient, edits in placeEfficient, edits in place
Append performanceSlowFastSlower than StringBuilder
Modification methodsNone (no in-place edit)append, insert, delete, replaceappend, insert, delete, replace
Best forFixed or rarely changed textFrequent edits, single threadFrequent edits, many threads
String buildingInefficientEfficientEfficient
Multi-threadingSafe but not for buildingNot safe for shared editsSafe for shared edits
Memory on editsNew allocation each changeMemory-efficient bufferBuffer plus lock overhead
Heavy manipulationNot advisedRecommendedRecommended (concurrent)
Introduced inJDK 1.0JDK 1.5JDK 1.0

Code and Performance

Diagram showing String creating a new object for every append while StringBuilder modifies a single object in place
Each String append makes a new object; StringBuilder edits one object in place.

The same “build a greeting” task shows the difference across all three classes.

public class BuildText {
    public static void main(String[] args) {
        // Using String: each += makes a new object
        String result = "Hello";
        result += ", ";
        result += "world";
        System.out.println(result);

        // Using StringBuilder: edits one buffer, fast
        StringBuilder sb = new StringBuilder();
        sb.append("Hello");
        sb.append(", ");
        sb.append("world");
        System.out.println(sb.toString());

        // Using StringBuffer: same, but thread-safe
        StringBuffer sbf = new StringBuffer();
        sbf.append("Hello");
        sbf.append(", ");
        sbf.append("world");
        System.out.println(sbf.toString());
    }
}

The loop trap. The clearest performance gap appears when you concatenate in a loop. Joining n pieces with String += rebuilds the whole text each time, so the cost grows roughly with the square of n. Doing the same with a StringBuilder appends into one buffer, so the cost grows only linearly. Therefore a StringBuilder can be dramatically faster for large loops.

Step-by-step:

  1. Create a String, a StringBuilder, or a StringBuffer, depending on your need.
  2. Use the right methods to concatenate or edit the text.
  3. Call toString() on a StringBuilder or StringBuffer to get the final String.

Best practices:

  • Use String when the content rarely changes.
  • Use StringBuilder for mutable edits in single-threaded code.
  • Use StringBuffer only when several threads share the buffer.

Common pitfall: concatenating with + inside a loop, which creates many intermediate String objects. Solution: build the text with a StringBuilder instead, then convert once at the end.

When to Use Which

You choose by asking two questions: does the text change, and do threads share it?

Use a String when the text is fixed, such as a constant, a key, or a label. Since it never changes, immutability is a feature, not a cost. So String keeps simple values simple and safe.

Use a StringBuilder when you build or edit text in one thread, such as assembling a report or joining tokens in a loop. Because it edits in place with no locking, it is the fastest option. Therefore it is the everyday default for string building.

Use a StringBuffer only when more than one thread edits the same buffer. Its synchronised methods keep the data safe, at a small speed cost. So reach for it purely when concurrency demands it, not by habit.

Interview Questions

String is immutable so it can be cached in the string pool, shared safely across threads, and used as a stable key in maps. Because the value never changes, the JVM can reuse and hash it safely. That design trades cheap edits for safety and sharing.

Both are mutable and share the same methods, so the only real difference is synchronisation. StringBuffer marks its methods synchronized, which makes it thread-safe but slower. StringBuilder skips the locking, so it is faster but unsafe across threads.

Each += on a String copies the whole text into a brand-new object, so a loop of n appends does roughly n-squared work. A StringBuilder instead appends into one buffer, so the same loop is closer to linear. Therefore StringBuilder is far faster for large loops.

For building or editing text, StringBuilder is the default, because it is mutable and fast without locking. Use plain String for fixed values, and switch to StringBuffer only when threads share the buffer. So most single-threaded code should reach for StringBuilder first.

Frequently Asked Questions

String is immutable, so once created its value cannot change. StringBuilder is mutable, so it allows edits without a new object. StringBuffer is like StringBuilder but thread-safe, since its methods are synchronised. So they differ in mutability and thread safety.

Use String when the value will not change often, since it is immutable. It is ideal for constants, literals, and keys where the content stays fixed. So String fits stable text rather than heavy building.

StringBuilder suits cases where you concatenate or modify strings frequently. Because it is mutable, it is far more efficient than String for repeated edits. So it is the go-to class for building text in a single thread.

Choose StringBuffer when your application needs thread safety for string edits. Its methods are synchronised, so it is safe when several threads touch the same buffer. So it fits multi-threaded string manipulation, despite a small speed cost.

Yes. String is the least efficient for frequent edits because of immutability. StringBuilder is faster than StringBuffer, since it is not synchronised. However, if thread safety matters, StringBuffer may be necessary despite its overhead.

During heavy editing, yes, because each String change allocates a new object and leaves the old one for the garbage collector. A StringBuilder reuses one growing buffer, so it wastes far less memory. For a single fixed value, though, a plain String is perfectly lean.

Wrapping Up

String, StringBuilder, and StringBuffer solve the same job at three trade-off points. String is immutable and safe but slow to edit, StringBuilder is mutable and fast, and StringBuffer is mutable and thread-safe.

Remember the simple rule: String for fixed text, StringBuilder for fast single-threaded building, and StringBuffer only when threads share the buffer. Weighing mutability against thread safety answers most exam and interview questions on the three.

Related reading on DiffStudy:


Whatsapp-color Created with Sketch.

By Arun Kumar

Full Stack Developer with a BE in Computer Science, working with React, Next.js, Node.js, MongoDB, and AI/ML tools. Founder of DiffStudy — built to help CS students ace GATE and university exams, and keep developers up to date across AI, cloud, system design, web development, and every field of computer science. Every article is written from real hands-on experience, not just theory.

Leave a Reply

Your email address will not be published. Required fields are marked *


You cannot copy content of this page