Java Reference
In-Depth Information
Discussion
An object of one of the
StringBuilder
classes basically represents a collection of charac-
ters. It is similar to a
String
object, but, as mentioned,
String
s are immutable.
StringBuilder
s are mutable and designed for, well, building
String
s. You typically con-
struct a
StringBuilder
, invoke the methods needed to get the character sequence just the
way you want it, and then call
toString()
to generate a
String
representing the same char-
acter sequence for use in most of the Java API, which deals in
String
s.
StringBuffer
is historical—it's been around since the beginning of time. Some of its meth-
ods are synchronized (see
Synchronizing Threads with the synchronized Keyword
), which
involves unneeded overhead in a single-threaded context. In Java 5, this class was “split” in-
to
StringBuffer
(which is synchronized) and
StringBuilder
(which is not synchronized);
thus, it is faster and preferable for single-threaded use. Another new class,
Ab-
stractStringBuilder
, is the parent of both. In the following discussion, I'll use “the
StringBuilder
classes” to refer to all three because they mostly have the same methods.
The topic's example code provides a
StringBuilderDemo
and a
StringBufferDemo
. Except
for the fact that
StringBuilder
is not threadsafe, these API classes are identical and can be
used interchangeably, so my two demo programs are almost identical except that each one
uses the appropriate builder class.
The
StringBuilder
classes have a variety of methods for inserting, replacing, and otherwise
modifying a given
StringBuilder
. Conveniently, the
append()
methods return a reference
to the
StringBuilder
itself, so statements like
.append(…).append(…)
are fairly common.
of concatenating strings.
Example 3-2. StringBuilderDemo.java
public
public class
class
StringBuilderDemo
StringBuilderDemo
{
public
public static
static
void
void
main
(
String
[]
argv
) {
String s1
=
"Hello"
+
", "
+
"World"
;
System
.
out
.
println
(
s1
);
// Build a StringBuilder, and append some things to it.
StringBuilder sb2
=
new
new
StringBuilder
();
sb2
.
append
(
"Hello"
);
sb2
.
append
(
','
);
sb2
.
append
(
' '
);