Difference Between String and StringBuffer

Naveen AnamaneniUpdated · 3 min read

Think of a String as a printed page and a StringBuffer as a whiteboard. To change a printed page, you have to print a whole new page; the whiteboard you just edit. Both hold text, and both can produce the same final words, but they suit very different jobs. This question ("String vs StringBuffer") appears in almost every Java interview, so here's the full comparison with an example that shows each difference.

Side by Side in Code

Versus.java▶ Try it
public class Versus {
    public static void main(String[] args) {
        String s = "Hi";
        s.concat(" Navika");
        System.out.println(s);
 
        StringBuffer sb = new StringBuffer("Hi");
        sb.append(" Navika");
        System.out.println(sb);
 
        System.out.println("Hi".equals("Hi"));
        StringBuffer x = new StringBuffer("Hi");
        System.out.println(x.equals(new StringBuffer("Hi")));
    }
}
Output
Hi
Hi Navika
true
false

How it works

  1. s.concat(" Navika") built a new string and threw it away; s is still "Hi". String is immutable.
  2. sb.append(" Navika") changed the buffer itself. StringBuffer is mutable.
  3. String overrides equals to compare text; StringBuffer doesn't, so two buffers with the same text aren't equals.

The Full Comparison

StringStringBuffer
Can the text change?No (immutable)Yes (mutable)
A "change" createsA new objectNothing new; the same object is edited
Thread safetySafe, because nothing can changeSafe, because methods are synchronized
equalsCompares textCompares references (not overridden)
hashCodeBased on text, cachedIdentity-based
String poolLiterals are pooledNever pooled
Joining with +SupportedNot supported; use append
Speed for many changesSlow (copies every time)Fast
Typical useValues, keys, messages, anything stored or sharedBuilding text in many steps across threads
SinceJava 1.0Java 1.0

Common Mistakes

Storing a StringBuffer as a map key or in a set. Its equals and hashCode don't look at the text.

Returning a StringBuffer from a method that should return text. Return sb.toString(), so callers can't change it.

Using String with += in a big loop. That's the slow case; use a builder.

Interview Corner

What is the difference between String and StringBuffer?

String is immutable: its value can't change, every modification creates a new object, literals are pooled, and equals compares content. StringBuffer is mutable: methods such as append and insert modify the same object, it's synchronized and therefore thread-safe, it isn't pooled, and it doesn't override equals, so it compares references. Use String for values that are stored and shared, and a buffer for building text through many changes.

Practice

  1. Easy: Write the same 5-step text-building code with String and with StringBuffer, printing the variable after each step. Where do they differ?
  2. Harder: Put two StringBuffer objects with the same text into a HashSet and print the set's size. Then put their toString() results in and compare.

Quick check: String vs StringBuffer

4 questions
1Which is mutable?
2new StringBuffer("a").equals(new StringBuffer("a")) is:
3Which is pooled?
4Which should you use as a HashMap key?

Key Takeaways

Was this tutorial helpful?

Lesson 200 of 482