Difference Between String and StringBuffer in Java
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
| Feature | String | StringBuffer |
|---|---|---|
| Mutability | Immutable | Mutable |
| Thread safety | Safe to share, because it never changes | Safe for single calls (synchronized methods) |
| Repeated changes | Each change creates a new object | Changes one internal buffer |
| Storage | Literals are pooled and shared | Each buffer is a separate object |
equals() | Compares content | Not overridden; compares references |
| Map key | Good choice | Poor choice |
| Introduced | Java 1.0 | Java 1.0 |
3. Class Hierarchy Diagram
Swipe sideways to see the whole diagram.
CharSequence(interface): both classes can be passed to any method that accepts aCharSequence, such asString.contentEquals().Comparable<T>(interface): both compare content withcompareTo();StringBuffergained it in Java 11.Serializable(interface): both can be serialized.- Superclasses:
StringextendsObject.StringBufferextends the package-privateAbstractStringBuilder, which the Javadoc hides, so it listsObjectas the direct superclass.
4. Example 1: Editing a Ticket Code
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));
}
}
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
toUpperCase()returns a newString;codestill holds the original text.code.concat("-X")also returns a new string, but the result is ignored, so it has no effect. This is a common bug.append()andreplace()change the buffer itself, andappend()returns the same object.
5. Example 2: Using Text as a Map Key
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));
}
}
String key : Window seat StringBuffer key : null equals() : false contentEquals() : true compareTo() == 0 : true
How the code works
Stringoverridesequals()andhashCode(), so a differentStringobject with the same text finds the entry.StringBufferkeeps the reference-based versions fromObject, so the lookup returnsnull.- To compare content, use
contentEquals()orcompareTo()(Java 11+).
6. Example 3: Building a Receipt in a Loop
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());
}
}
====================== Masala Dosa 120 Filter Coffee 45 Idli 60 ---------------------- TOTAL 225 Buffer length after reset: 0
How the code works
- One buffer collects every line. Building the same text with
+=would create a newStringon each iteration. repeat()(Java 21+) appends a separator without a loop.toString()takes an immutable snapshot, andsetLength(0)empties the buffer for reuse without affecting that snapshot.
7. Important Features and Characteristics
- Immutability: a
Stringcan be shared freely, cached, and used as a map key. Literals are interned in the string pool. - Mutability: a
StringBufferreuses its internal storage, which grows automatically;ensureCapacity()andtrimToSize()manage it. - Synchronization: each
StringBuffermethod is synchronized, but a sequence of calls is not atomic. - Equality:
Stringcompares content;StringBuffercompares references.
8. Advantages and Limitations
| Class | Advantages | Limitations |
|---|---|---|
String | Safe to share, hashable, and supported by the string pool. | Every modification creates a new object. |
StringBuffer | Efficient repeated edits; individual calls are thread-safe. | Locking overhead; equals() compares references; usually unnecessary in single-threaded code. |
9. Constructors
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
| Operation | String (returns a new String) | StringBuffer (changes itself) |
|---|---|---|
| Add text | concat(s), + | append(x) |
| Insert text | Not available | insert(offset, x) |
| Replace | replace(a, b) | replace(start, end, s) |
| Remove | substring(...) | delete(start, end), deleteCharAt(i) |
| Reverse | Not available | reverse() |
| Repeat | repeat(n) (Java 11+) | repeat(cs, n) (Java 21+) |
| Read | charAt(i), length(), indexOf(s) | charAt(i), length(), indexOf(s) |
11. Changes up to Java 25
| Version | Change |
|---|---|
| Java 5 | StringBuilder added as an unsynchronized alternative to StringBuffer. |
| Java 11 | String gained repeat(), strip() and isBlank(); StringBuffer became Comparable. |
| Java 15 | Text blocks and String.stripIndent(). |
| Java 21 | StringBuffer.repeat(). |
| Java 25 | CharSequence.getChars() became a default interface method. |
12. When to Use String vs StringBuffer
- Use
Stringfor 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
StringBufferonly 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; writes = s.trim();. - Using
+=in a loop. Append to one builder instead. - Comparing buffers with
equals(). UsecontentEquals()orcompareTo(). - 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
Stringis immutable;StringBufferis 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
StringBuilderoverStringBufferunless threads share the buffer.