Java Reference
In-Depth Information
StringBuffer aString = new StringBuffer("A stitch in time");
int theLength = aString.length();
If the object aString was defined as in the declaration above, the variable theLength will have the
value 16. However, the capacity of the object is larger, as illustrated in the diagram.
When you create a StringBuffer object from an existing string, the capacity will be the length of the
string plus 16. Both the capacity and the length are in units of Unicode characters, so twice as many
bytes will be occupied in memory.
The capacity of a StringBuffer object is not fixed though. For instance, you can create a
StringBuffer object with a given capacity by specifying the capacity when you declare it:
StringBuffer newString = new StringBuffer(50);
This will create an object, newString , with the capacity to store 50 characters. If you omitted the
capacity value in this declaration, the object would have a default capacity of 16 characters.
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 is a container in which you can store any string and
therefore has a capacity - a potential for storing strings up to a given size. Although you can set it, the
capacity is unimportant in the sense that it is just a measure of how much memory is available to store
Unicode characters at this particular point in time. You can get by without worrying about the capacity
of a StringBuffer object since the capacity required to cope with what your program is doing will
always be provided automatically. It just gets increased as necessary.
On the other hand, 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, extra memory will need to be
allocated, which will take time. 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();
This method will return the number of Unicode characters the object can currently hold. For aString
defined as shown, this will be 32. When you create a StringBuffer object containing a string, its
capacity will be 16 characters greater than the minimum necessary to hold the string.
Search WWH ::




Custom Search