Home

StringBuffer

StringBuffer is a class in the Java standard library that represents a mutable sequence of characters. Unlike String, which is immutable, a StringBuffer can be modified in place, avoiding the creation of intermediate objects during repeated concatenation. StringBuffer is part of java.lang and is designed to be thread-safe through synchronized methods, making it suitable for use in multi-threaded contexts where a shared string-like buffer is updated by multiple threads.

Typical operations include appending, inserting, deleting, and replacing characters. Common methods are append, insert, delete, deleteCharAt,

A key distinction from the related class StringBuilder is synchronization. StringBuffer methods are synchronized, which enforces

StringBuffer has several constructors: a no-argument constructor that creates an empty buffer with a default capacity,

In practice, StringBuffer is used when a mutable string is built incrementally in a multi-threaded environment,

setCharAt,
reverse,
setLength,
and
capacity-related
methods
such
as
capacity
and
ensureCapacity.
The
class
also
implements
CharSequence
and
Appendable,
and
provides
conversion
to
String
via
toString.
safe
access
from
multiple
threads
but
incurs
overhead.
For
single-threaded
code,
StringBuilder
offers
similar
functionality
with
better
performance.
If
thread
safety
is
required
only
for
specific
sequences,
external
synchronization
around
a
StringBuilder
may
be
preferred.
a
constructor
that
accepts
an
initial
capacity,
and
a
constructor
that
initializes
the
buffer
with
the
contents
of
a
given
string.
Internally,
StringBuffer
maintains
a
character
array
and
a
count
of
characters;
it
grows
the
array
when
needed,
typically
by
expanding
capacity.
while
StringBuilder
is
chosen
for
non-concurrent
use
cases.
The
toString
method
returns
an
immutable
String
containing
the
current
contents.