Java Reference
In-Depth Information
object than just the string that it contains initially, and of course, a string literal is a
String
object by defin-
ition.
You can also create a
StringBuffer
object using a reference stored in a variable of type
String
:
String phrase = "Experience is what you get when you're expecting something
else.";
StringBuffer buffer = new StringBuffer(phrase);
The
StringBuffer
object,
buffer
, contains a string that is the same as that encapsulated by the
String
object,
phrase
.
You can just create the
StringBuffer
variable, in much the same way as you created a
String
variable:
StringBuffer myString = null;
This variable does not refer to anything until you initialize it with a defined
StringBuffer
object. For
example, you could write:
myString = new StringBuffer("Many a mickle makes a muckle");
This statement creates a new
StringBuffer
object encapsulating the string
"Many a mickle makes a
muckle"
and stores the reference to this object in
myString
. You can also initialize a
StringBuffer
vari-
able with an existing
StringBuffer
object:
StringBuffer aString = myString;
Both
myString
and
aString
now refer to a single
StringBuffer
object.
The Capacity of a StringBuffer Object
The
String
objects that you have been using each contain a fixed string, and when you create a
String
object, memory is allocated to accommodate however many Unicode characters are in the string it encapsu-
lates. Everything is fixed so memory usage is not a problem. A
StringBuffer
object is a little different. It
contains a block of memory called a
buffer
, which may or may not contain a string, and if it does, the string
need not occupy the entire buffer. Thus, the length of a string in a
StringBuffer
object can be different
from the length of the buffer that the object contains. The length of the buffer is referred to as the
capacity
of the
StringBuffer
object.
After you have created a
StringBuffer
object, you can find the length of the string it contains, by using
the
length()
method for the object:
StringBuffer aString = new StringBuffer("A stitch in time");
int theLength = aString.length();
If the object
aString
were defined as in the preceding declaration, the variable
theLength
would have
the value 16. However, the capacity of the object is larger, as illustrated in
Figure 4-12
.