Difference Between String and StringBuffer in Java
String and StringBuffer both represent sequences of characters, but they behave very differently:
Stringis immutable. Every "change", such as concatenation ortoUpperCase(), creates a new object. Literals are shared through the string pool.StringBufferis mutable. Methods such asappend,insertandreversemodify the same object, and every method is synchronized.
1. Comparison Table
| Aspect | String | StringBuffer |
|---|---|---|
| Mutability | Immutable | Mutable |
| Thread safety | Safe (cannot change) | Safe (synchronized methods) |
| Repeated modification | Slow: creates new objects | Fast: modifies an internal buffer |
| Storage | Literals in the string pool; objects on the heap | Heap only |
equals() | Compares content | Compares references (not overridden) |
hashCode() | Content-based, cached | Identity-based |
| Concatenation | +, concat() | append() |
| Extra operations | Rich read-only API | insert, delete, reverse, setCharAt, capacity control |
| Good as a map key | Yes | No |
2. Immutable vs Mutable
public class MutabilityDemo {
public static void main(String[] args) {
String s = "Java";
String s2 = s.concat(" Tutorial"); // new object; s unchanged
System.out.println("String : s = " + s + ", s2 = " + s2 + ", same object? " + (s == s2));
StringBuffer sb = new StringBuffer("Java");
StringBuffer sb2 = sb.append(" Tutorial"); // same object modified in place
System.out.println("StringBuffer : sb = " + sb + ", same object? " + (sb == sb2));
// equals(): String compares content, StringBuffer compares identity
System.out.println("\"ab\".equals(new String(\"ab\")) : " + "ab".equals(new String("ab")));
System.out.println("new StringBuffer(\"ab\").equals(another) : " + new StringBuffer("ab").equals(new StringBuffer("ab")));
System.out.println("contentEquals : " + "ab".contentEquals(new StringBuffer("ab")));
// Converting between them
String back = sb.toString();
StringBuffer fromString = new StringBuffer(back).reverse();
System.out.println("toString / reverse : " + back + " / " + fromString);
}
}
String : s = Java, s2 = Java Tutorial, same object? false
StringBuffer : sb = Java Tutorial, same object? true
"ab".equals(new String("ab")) : true
new StringBuffer("ab").equals(another) : false
contentEquals : true
toString / reverse : Java Tutorial / lairotuT avaJ
Be careful with equals: two buffers with the same text are not equal. Compare their toString() values or use contentEquals.
3. Performance of Repeated Concatenation
public class ConcatCost {
public static void main(String[] args) {
int n = 30_000;
long t0 = System.nanoTime();
String s = "";
for (int i = 0; i < n; i++) s += "x";
long t1 = System.nanoTime();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) sb.append("x");
long t2 = System.nanoTime();
System.out.printf("String += : %4d ms%n", (t1 - t0) / 1_000_000);
System.out.printf("StringBuffer.append : %4d ms%n", (t2 - t1) / 1_000_000);
System.out.println("same text: " + s.equals(sb.toString()));
}
}
String += : 49 ms StringBuffer.append : 1 ms same text: true
Each += copies the whole string built so far, making loops quadratic. append adds to a growing buffer instead.
4. When to Use Which
String: text that does not change, constants, map keys, method parameters and return values. This is almost always the right type to expose in APIs.StringBuilder(notStringBuffer): building text in loops within one thread, which is the usual case.StringBuffer: only when one buffer is genuinely shared between threads, or a legacy API requires it.
See StringBuffer vs StringBuilder.
5. Summary
Stringis immutable;StringBufferis mutable and synchronized.- Repeated changes are much faster with a buffer than with
Stringconcatenation. String.equalscompares content;StringBuffer.equalscompares identity.- Use
Stringfor values,StringBuilderfor building,StringBufferonly for shared buffers.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is the main difference between String and StringBuffer?
String is immutable; StringBuffer is mutable and can be changed in place.
Q2. Is String thread-safe?
Yes. Immutable objects can be shared safely between threads.
Q3. Is StringBuffer thread-safe?
Yes. Its public methods are synchronized, although compound sequences of calls still need external locking.
Q4. Which is faster for concatenation in a loop?
StringBuffer (and even more so StringBuilder). String += creates a new object each time.
Q5. Why does StringBuffer.equals() return false for equal text?
It does not override equals, so it compares references. Use toString().equals(...), compareTo or contentEquals.
Q6. How do I convert a StringBuffer to a String?
Call toString().
Q7. How do I convert a String to a StringBuffer?
new StringBuffer(text).
Q8. Are StringBuffer objects stored in the string pool?
No. Only string literals and interned strings are pooled.
Q9. Why is String immutable?
For safe sharing in the string pool, security of values like file paths, thread safety and reliable cached hash codes for map keys.
Q10. Can I use StringBuffer as a HashMap key?
It is a bad idea: it is mutable and uses identity-based equality. Use a String.
Q11. Does the + operator use StringBuffer?
Very old compilers used StringBuffer; later ones used StringBuilder, and since Java 9 invokedynamic string concatenation.
Q12. Which uses more memory?
Repeatedly modified Strings create many temporary objects. A StringBuffer may keep spare capacity but avoids that churn.
Q13. What is the default capacity of StringBuffer?
16 characters, growing to (old × 2) + 2 when needed.
Q14. Can a String be reversed?
Not in place. Use new StringBuilder(s).reverse().toString().
Q15. Which classes implement CharSequence?
String, StringBuffer, StringBuilder and CharBuffer, among others.
Q16. Should methods accept String or StringBuffer?
Usually String, or CharSequence if any character sequence is acceptable.
Q17. Is StringBuffer legacy?
It is still supported, but StringBuilder replaced it for most uses in Java 5.
Q18. Does String have a capacity?
No. A string's length is fixed when it is created.
Q19. Which is final?
Both classes are final and cannot be extended.
Q20. Is this a common interview question?
Yes. Cover mutability, thread safety, performance, the string pool and equals behaviour, and mention StringBuilder.