Java Reference
In-Depth Information
10.11.2
java.lang.StringBuffer
String objects cannot be altered. Once they are created, they are
immutable
objects.
Concatenating two strings together creates a whole new string object in memory:
String str ="This is ";
str
=
str +
"
a new string object
"
;
The
str
variable now references a new
String
object that holds
“This is
a new string object
„
. The
String
class maintains a pool of strings in
memory. String literals are saved there and new strings are added as they are
created. Extensive string manipulation with lots of new strings created with the
String
append operation can therefore result in lots of memory taken up by
unneeded strings. Note, however, that if two string literals are the same, the
second string reference will point to the string already in the pool rather than
create a duplicate.
The class
java.lang.StringBuffer
provides a much more memory effi-
cient tool for building strings. The class works as follows:
StringBuffer strb = new StringBuffer ("This is ");
strb.append ("a new string object");
System.out.println (strb.toString ());
Yo u first create an instance of the
StringBuffer
class and then append new
strings to it using the
append()
method. Internally, the class holds a large
character array. Appending strings just involves filling places in the array with
new
char
values. It does not need to create any new objects. If the array is already
filled when you try to do an
append()
, then
StringBuffer
creates a larger
array and copies the old characters into the new one. All this happens internally,
completely transparently to you.
10.11.3
java.lang.StringBuilder
Java Version 5.0 added the
StringBuilder
class, which is a drop-in replace-
ment for
StringBuffer
in cases where thread safety is not an issue.
Because
StringBuilder
is not synchronized, it has better performance than
StringBuffer
.Ingeneral, you should use
StringBuilder
in preference
over
StringBuffer
.Infact, the J2SE 5.0
javac
compiler normally uses
StringBuilder
instead of
StringBuffer
whenever you perform string con-
catenation, as in
System.out.println ("The result is " + result);
All
the
methods
available
on
StringBuffer
are
also
available
on
StringBuilder
,soitreally is a drop-in replacement.
Search WWH ::
Custom Search