Sunday, July 8, 2012

length( ) and capacity( ) in java

The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms:

  • int length( ) 
  • int capacity( ) 
Here is an example:

 
// StringBuffer length vs. capacity. 
 
class StringBufferDemo
 { 
 
   public static void main(String args[]) {
   StringBuffer sb = new StringBuffer("Hello");
   System.out.println("buffer = " + sb);
   System.out.println("length = " + sb.length());
   System.out.println("capacity = " + sb.capacity());
}
}


Here is the output of this program, which shows how StringBuffer reserves extra


space for additional manipulations:
buffer = Hello
length = 5
capacity = 21


Since sb is initialized with the string “Hello” when it is created, its length is 5. Its
capacity is 21 because room for 16 additional characters is automatically added. 
ensureCapacity( )

 If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form: 

  • void ensureCapacity(int capacity)
 Here, capacity specifies the size of the buffer. 
setLength( ) 

To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is shown here: 
void setLength(int len) 
Here, len specifies the length of the buffer. 
This value must be nonnegative. When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost. 
 The setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer.

No comments:

Post a Comment