Java Reference
In-Depth Information
The ensureCapacity() method enables you to change the default capacity of a StringBuffer
object. You specify the minimum capacity you need as the argument to the method, for example:
aString.ensureCapacity(40);
If the current capacity of the aString object is less than 40, this will increase the capacity of aString
by allocating a new larger buffer, but not necessarily with a capacity of 40. The capacity will be the
larger of either the value you specify, 40 in this case, or twice the current capacity plus 2, which is 66,
given that aString is defined as before.
Changing the Length for a StringBuffer Object
You can change the length of the string contained in a StringBuffer object with the method
setLength() . Note that the length is a property of the string the object holds, as opposed to the
capacity, which is a property of the string buffer. When you increase the length for a StringBuffer
object, the extra characters will contain ' \u0000 '. A more common use of this method would be to
decrease the length, in which case the string will be truncated. If aString contains " A stitch in
time ", the statement:
aString.setLength(8);
will result in aString containing the string " A stitch ", and the value returned by the length()
method will be 8. The characters that were cut from the end of the string by this operation are lost.
To increase the length to what it was before, you could write:
aString.setLength(16);
Now aString will contain:
" A stitch\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 "
The setLength() method does not affect the capacity of the object unless you set the length to be
greater than the capacity. In this case the capacity will be increased to accommodate the new string
length to a value that is twice the original capacity plus two if the length you set is less than this value. If
you specify a length that is greater than twice the original capacity plus two, the new capacity will be the
same as the length you set. If the capacity of aString is 66, executing the statement.
aString.setLength(100);
will set the capacity of the object, aString , to 134. If you supplied a value for the length of 150, then
the new capacity would be 150. You must not specify a negative length here. If you do a
StringIndexOutOfBoundsException exception will be thrown.
Search WWH ::




Custom Search