00:00

Difference Between String and StringBuffer in Java

Last updated:

String and StringBuffer both store text, but they follow opposite rules. A String never changes after it is created, while a StringBuffer is designed to be changed again and again.

Choosing the wrong one leads to wasted objects, subtle equality bugs or unnecessary locking, so it helps to understand how each class behaves.

1. What Are String and StringBuffer?

A String is an immutable sequence of characters. Methods such as toUpperCase() or concat() return a new object and leave the original untouched. Because strings never change, the JVM can share string literals through the string pool.

A StringBuffer is a mutable, thread-safe sequence of characters. Methods such as append() and insert() change the same object, and its methods are synchronized.

2. String vs StringBuffer: Key Differences

FeatureStringStringBuffer
MutabilityImmutableMutable
Thread safetySafe to share, because it never changesSafe for single calls (synchronized methods)
Repeated changesEach change creates a new objectChanges one internal buffer
StorageLiterals are pooled and sharedEach buffer is a separate object
equals()Compares contentNot overridden; compares references
Map keyGood choicePoor choice
IntroducedJava 1.0Java 1.0

3. Class Hierarchy Diagram

String and StringBuffer class hierarchyString and StringBuffer are final classes. Both implement Serializable, CharSequence and Comparable. String extends Object and also implements Constable and ConstantDesc; StringBuffer extends the package-private AbstractStringBuilder and also implements Appendable.«interface» · java.ioSerializable«interface» · java.langCharSequencelength(), charAt(int)subSequence(int, int)«interface» · java.langComparable<T>compareTo(T) †† StringBuffer: since Java 11«final class» · Java 1.0Stringextends Objectimmutable; literals pooledConstable, ConstantDesc †† also implemented, Java 12+«final class» · Java 1.0StringBufferextends AbstractStringBuildermutable; synchronizedalso implements Appendableimplementsinterfaceclass

Swipe sideways to see the whole diagram.

  • CharSequence (interface): both classes can be passed to any method that accepts a CharSequence, such as String.contentEquals().
  • Comparable<T> (interface): both compare content with compareTo(); StringBuffer gained it in Java 11.
  • Serializable (interface): both can be serialized.
  • Superclasses: String extends Object. StringBuffer extends the package-private AbstractStringBuilder, which the Javadoc hides, so it lists Object as the direct superclass.

4. Example 1: Editing a Ticket Code

TicketCode.java
public class TicketCode {
    public static void main(String[] args) {
        // String: every "change" returns a new object
        String code = "blr-del-0412";
        String upper = code.toUpperCase();     // new String
        code.concat("-X");                     // result ignored, so nothing happens
        System.out.println("String original : " + code);
        System.out.println("String upper    : " + upper);
        System.out.println("Same object?    : " + (code == upper));

        // StringBuffer: methods change the same object
        StringBuffer ticket = new StringBuffer("blr-del-0412");
        StringBuffer result = ticket.append("-X");    // returns the same buffer
        ticket.replace(0, 7, "BLR-DEL");
        System.out.println("Buffer          : " + ticket);
        System.out.println("Same object?    : " + (ticket == result));
    }
}
Output
String original : blr-del-0412
String upper    : BLR-DEL-0412
Same object?    : false
Buffer          : BLR-DEL-0412-X
Same object?    : true

How the code works

  1. toUpperCase() returns a new String; code still holds the original text.
  2. code.concat("-X") also returns a new string, but the result is ignored, so it has no effect. This is a common bug.
  3. append() and replace() change the buffer itself, and append() returns the same object.

5. Example 2: Using Text as a Map Key

SeatLookup.java
import java.util.HashMap;
import java.util.Map;

public class SeatLookup {
    public static void main(String[] args) {
        // String keys compare by content
        Map<String, String> byString = new HashMap<>();
        byString.put("A12", "Window seat");
        System.out.println("String key       : " + byString.get(new String("A12")));

        // StringBuffer keys compare by reference (equals is not overridden)
        Map<StringBuffer, String> byBuffer = new HashMap<>();
        byBuffer.put(new StringBuffer("A12"), "Window seat");
        System.out.println("StringBuffer key : " + byBuffer.get(new StringBuffer("A12")));

        // Comparing content correctly
        StringBuffer typed = new StringBuffer("A12");
        System.out.println("equals()         : " + typed.equals(new StringBuffer("A12")));
        System.out.println("contentEquals()  : " + "A12".contentEquals(typed));
        System.out.println("compareTo() == 0 : " + (typed.compareTo(new StringBuffer("A12")) == 0));
    }
}
Output
String key       : Window seat
StringBuffer key : null
equals()         : false
contentEquals()  : true
compareTo() == 0 : true

How the code works

  1. String overrides equals() and hashCode(), so a different String object with the same text finds the entry.
  2. StringBuffer keeps the reference-based versions from Object, so the lookup returns null.
  3. To compare content, use contentEquals() or compareTo() (Java 11+).

6. Example 3: Building a Receipt in a Loop

ReceiptBuilder.java
public class ReceiptBuilder {
    public static void main(String[] args) {
        String[] items = {"Masala Dosa", "Filter Coffee", "Idli"};
        int[] prices = {120, 45, 60};

        StringBuffer receipt = new StringBuffer(96);  // one object for the whole receipt
        receipt.repeat('=', 22).append('\n');         // Java 21+
        int total = 0;
        for (int i = 0; i < items.length; i++) {
            receipt.append(String.format("%-15s %6d\n", items[i], prices[i]));
            total += prices[i];
        }
        receipt.repeat('-', 22).append('\n');
        receipt.append(String.format("%-15s %6d", "TOTAL", total));

        String finalText = receipt.toString();        // immutable snapshot
        receipt.setLength(0);                          // reuse the buffer
        System.out.println(finalText);
        System.out.println("Buffer length after reset: " + receipt.length());
    }
}
Output
======================
Masala Dosa        120
Filter Coffee       45
Idli                60
----------------------
TOTAL              225
Buffer length after reset: 0

How the code works

  1. One buffer collects every line. Building the same text with += would create a new String on each iteration.
  2. repeat() (Java 21+) appends a separator without a loop.
  3. toString() takes an immutable snapshot, and setLength(0) empties the buffer for reuse without affecting that snapshot.

7. Important Features and Characteristics

  • Immutability: a String can be shared freely, cached, and used as a map key. Literals are interned in the string pool.
  • Mutability: a StringBuffer reuses its internal storage, which grows automatically; ensureCapacity() and trimToSize() manage it.
  • Synchronization: each StringBuffer method is synchronized, but a sequence of calls is not atomic.
  • Equality: String compares content; StringBuffer compares references.

8. Advantages and Limitations

ClassAdvantagesLimitations
StringSafe to share, hashable, and supported by the string pool.Every modification creates a new object.
StringBufferEfficient repeated edits; individual calls are thread-safe.Locking overhead; equals() compares references; usually unnecessary in single-threaded code.

9. Constructors

Constructors.java
String a = "Gate 7";                            // literal, taken from the string pool
String b = new String("Gate 7");                // always a new object (rarely needed)
String c = String.valueOf(42);                  // from another type
StringBuffer d = new StringBuffer();            // empty, capacity 16
StringBuffer e = new StringBuffer(64);          // empty, capacity 64
StringBuffer f = new StringBuffer("Gate 7");    // copy of the text, capacity 16 + 6

StringBuffer also accepts any CharSequence. Convert back with toString().

10. Common Methods

OperationString (returns a new String)StringBuffer (changes itself)
Add textconcat(s), +append(x)
Insert textNot availableinsert(offset, x)
Replacereplace(a, b)replace(start, end, s)
Removesubstring(...)delete(start, end), deleteCharAt(i)
ReverseNot availablereverse()
Repeatrepeat(n) (Java 11+)repeat(cs, n) (Java 21+)
ReadcharAt(i), length(), indexOf(s)charAt(i), length(), indexOf(s)

11. Changes up to Java 25

VersionChange
Java 5StringBuilder added as an unsynchronized alternative to StringBuffer.
Java 11String gained repeat(), strip() and isBlank(); StringBuffer became Comparable.
Java 15Text blocks and String.stripIndent().
Java 21StringBuffer.repeat().
Java 25CharSequence.getChars() became a default interface method.

12. When to Use String vs StringBuffer

  • Use String for values that do not change: constants, map keys, method parameters and return values.
  • Use StringBuilder to build text inside one thread, which is the usual case.
  • Use StringBuffer only when several threads append to the same buffer, or an existing API requires it. See StringBuffer vs StringBuilder.

13. Common Mistakes and Best Practices

  • Ignoring a String method's result. s.trim(); does nothing; write s = s.trim();.
  • Using += in a loop. Append to one builder instead.
  • Comparing buffers with equals(). Use contentEquals() or compareTo().
  • Using a buffer as a map key. Convert it with toString() first.
  • Using new String("..."). It creates an extra object; use the literal.

14. Summary

  • String is immutable; StringBuffer is mutable and synchronized.
  • String methods return new objects; StringBuffer methods change the same object.
  • String.equals() compares content; StringBuffer.equals() compares references.
  • Use String for values and keys, and a builder for text that is assembled step by step.
  • Prefer StringBuilder over StringBuffer unless threads share the buffer.

15. References