Java Reference
In-Depth Information
Software Engineering Observation 14.1
StringBuilder
s are not thread safe. If multiple threads require access to the same
dynamic string information, use class
StringBuffer
in your code. Classes
StringBuilder
and
StringBuffer
provide identical capabilities, but class
StringBuffer
is thread safe.
For more details on threading, see Chapter 23.
Class
StringBuilder
provides four constructors. We demonstrate three of these in
Fig. 14.10. Line 8 uses the no-argument
StringBuilder
constructor to create a
String-
Builder
with no characters in it and an initial capacity of 16 characters (the default for a
StringBuilder
). Line 9 uses the
StringBuilder
constructor that takes an integer argu-
ment to create a
StringBuilder
with no characters in it and the initial capacity specified
by the integer argument (i.e.,
10
). Line 10 uses the
StringBuilder
constructor that takes
a
String
argument to create a
StringBuilder
containing the characters in the
String
ar-
gument. The initial capacity is the number of characters in the
String
argument plus 16.
Lines 12-14 implicitly use the method
toString
of class
StringBuilder
to output
the
StringBuilder
s with the
printf
method. In Section 14.4.4, we discuss how Java uses
StringBuilder
objects to implement the
+
and
+=
operators for string concatenation.
1
// Fig. 14.10: StringBuilderConstructors.java
2
// StringBuilder constructors.
3
4
public class
StringBuilderConstructors
5
{
6
public static void
main(String[] args)
7
{
8
StringBuilder buffer1 =
new
StringBuilder();
StringBuilder buffer2 =
new
StringBuilder(
10
);
StringBuilder buffer3 =
new
StringBuilder(
"hello"
);
9
10
11
12
System.out.printf(
"buffer1 = \"%s\"%n"
, buffer1);
13
System.out.printf(
"buffer2 = \"%s\"%n"
, buffer2);
14
System.out.printf(
"buffer3 = \"%s\"%n"
, buffer3);
15
}
16
}
// end class StringBuilderConstructors
buffer1 = ""
buffer2 = ""
buffer3 = "hello"
Fig. 14.10
|
StringBuilder
constructors.
ensureCapacity
Class
StringBuilder
provides methods
length
and
capacity
to return the number of
characters currently in a
StringBuilder
and the number of characters that can be stored