String
class, Java also provides StringBuffer
and StringBuilder
. The String
class is immutable, while these two helper classes implement the Builder pattern and are designed for modifying strings without the overhead of creating new objects for each modification.All methods in
StringBuffer
are synchronized. In Java 1.5, StringBuilder
was introduced as an unsynchronized alternative, which is similar to the difference between HashMap and Hashtable. Aside from synchronization, the two classes are almost identical in terms of available methods and constructors.String syntax sugar doesn't work for these builder classes:
- You can't create a
StringBuffer
orStringBuilder
with a literal; instead, you must use a constructor. - You can't concatenate strings using the
+
operator; instead, you use methods likeinsert
andappend
.
+
operator in constant expressions gets compiled into an interned string, but applied to non-constant expressions, it implicitly uses StringBuilder
behind the scenes.