Easy java core-java

Why is String immutable, and when do you use StringBuilder or StringBuffer?

The 30 second answer

A String can't change after it's created; methods like concat or toUpperCase return a new String. That makes strings safe to share between threads, safe as HashMap keys, safe for things like file paths and class names, and it lets the JVM reuse literals from the string pool. When I build a string in a loop I use StringBuilder, which is mutable and fast. StringBuffer is the old synchronized version; it's rarely needed now.

<!-- level: 1 --> <!-- must_know: true -->

  • The String Javadoc says strings are constant: their values cannot be changed after they are created, and because they are immutable they can be shared.
  • Why it matters: thread safety without locks, stable hash codes for map keys (String caches its hash), security for values such as file names and URLs that are checked and then used, and literal reuse through the string pool.
  • Cost: concatenating in a loop with += creates a new object on each iteration.
StringStringBuilderStringBuffer
MutableNoYesYes
Thread-safeYes (immutable)NoYes (synchronized)
UseValues, keys, constantsBuilding strings in one threadLegacy code shared across threads

The StringBuilder Javadoc describes it as compatible with StringBuffer "but with no guarantee of synchronization", and recommends it in preference to StringBuffer where possible because it will be faster in most implementations.

How many objects new String("java") creates is covered in How does the String pool work, and how many objects does new String create?.

Sources (2)
  1. Javadoc: java.lang.Stringdocs.oracle.com
  2. Javadoc: java.lang.StringBuilderdocs.oracle.com