Java Reference
In-Depth Information
When you create a
StringBuffer
object from an existing string, the capacity is the length of the string
plus 16. Both the capacity and the length are in units of Unicode characters, so twice as many bytes are oc-
cupied in memory.
The capacity of a
StringBuffer
object is not fixed, though. It grows automatically as you add to the
string to accommodate a string of any length. You can also specify the initial capacity when you create a
StringBuffer
object. For example, the following statement creates a
StringBuffer
object with a specific
value for the capacity:
StringBuffer newString = new StringBuffer(50);
This creates an object,
newString
, with the capacity to store 50 characters. If you omit the capacity value
in this declaration, the object has a default capacity of 16 characters. Thus, the
StringBuffer
object that
you create here has a buffer with a capacity of 50 characters that is initially empty — no string is stored in
it.
A
String
object is always a fixed string, so capacity is irrelevant — it is always just enough to hold the
characters in the string. A
StringBuffer
object, on the other hand, is a container in which you can store a
string of any length, and it has a capacity at any given instant for storing a string up to a given size. Although
you can set the capacity, it is unimportant in the sense that it is just a measure of how much memory is avail-
able to store Unicode characters at this particular point in time. You can get by without worrying about the
capacity of a
StringBuffer
object at all because the capacity required to cope with what your program is
doing is always provided automatically. It just gets increased as necessary.
So why have I mentioned the capacity of a
StringBuffer
object at all? While it's true you can use
StringBuffer
objects ignoring their capacity, the capacity of a
StringBuffer
object is important in the
sense that it affects the amount of overhead involved in storing and modifying a string. If the initial capacity
is small, and you store a string that is long, or you add to an existing string significantly, you need to allocate
extra memory. Allocating additional memory takes time, and if it occurs frequently, it can add a substantial
overhead to the processor time your program needs to complete the task. It is more efficient to make the
capacity of a
StringBuffer
sufficient for the needs of your program.
To find out what the capacity of a
StringBuffer
object is at any given time, you use the
capacity()
method for the object:
int theCapacity = aString.capacity();