Java Reference
In-Depth Information
The empty
String
on line 10 is instantiated, and then line 12 appends an
”a”
. However,
because the
String
object is immutable, a new
String
object is assigned to
alpha
and the
””
object becomes eligible for garbage collection. The next time through the loop,
alpha
is assigned a new
String
object
”ab”
and the
”a”
object becomes eligible for garbage col-
lection. The next iteration assigns
alpha
to
”abc”
and the
”ab”
object becomes eligible for
garbage collection, and so on.
This sequence of events continues, and after 26 iterations through the loop, a total of 27
objects are instantiated, 26 of which are immediately eligible for garbage collection. A bet-
ter technique in this situation would be to use the
StringBuffer
or
StringBuilder
classes,
which I discuss in detail in the next section.
The
StringBuilder
and
StringBuffer
Classes
The
java.lang
package contains two classes for representing strings as a mutable sequence
of characters:
StringBuilder
and
StringBuffer
. The
StringBuffer
class has been around
since the fi rst version of Java, while
StringBuilder
was added in J2SE 5.0. The two classes
have the exact same method signatures and constructor parameters. The only difference
between them is that
StringBuffer
is thread-safe and
StringBuilder
is not. If you are
working with arrays of characters in a multithreaded application, use the
StringBuffer
class. Otherwise, if threads are not an issue for your particular situation, use the
String-
Builder
class.
Let's look at an example. The following
for
loop is similar to the example in the previ-
ous section, except it uses a single
StringBuilder
object instead of 27
String
objects:
15. StringBuilder alpha = new StringBuilder(26);
16. for(char current = 'a'; current <= 'z'; current++) {
17. alpha.append(current);
18. }
19. System.out.println(alpha);
The
StringBuilder
class contains a constructor that takes in an
int
to represent the ini-
tial capacity. On line 15, a new
StringBuilder
object is instantiated with an initial capac-
ity of 26. This does not mean only 26 characters can appear in
alpha
. The capacity merely
specifi es an initial buffer. If the capacity of a
StringBuilder
object is reached, the length
of the
StringBuilder
object is automatically increased. We can improve performance if we
give a
StringBuilder
a capacity, but it does not affect the behavior of the object.
The call to
append
on line 17 increases the size of the
StringBuilder
object by one
each time through the
for
loop and appends the value of
current
to the end of
alpha
.
The
StringBuilder
object grows as needed, but there is only one instance in memory, as
Figure 4.2 shows.
Search WWH ::
Custom Search