Java StringBuffer Tutorial
Java provides two classes for string handling, String class and
StringBuffer class. StringBuffer is a mutable sequence of characters.
StringBuffer is like a String but the contents of the StringBuffer
can be modified once created.
StringBuffer Capacity
Each StringBuffer object has a capacity associated with it. The
capacity of the StringBuffer is the number of characters in can
hold. The capacity of the StringBuffer automatically increases as
we add more contents to it.
StringBuffer’s current capacity can be obtained by using
following method.
int capacity()
This method returns the current capacity of the StringBuffer object.
Example :
StringBuffer stringBuffer = new StringBuffer(“Hello World”);
System.out.println(stringBuffer.capacity());
This will print 27 (11 + 16) on console when run.
The actual number of characters in StringBuffer can be obtained
by following method.
int length()
Returns the actual number of characters contained in the StringBuffer.
Example :
StringBuffer stringBuffer = new StringBuffer(“Hello World”);
System.out.println(stringBuffer.length());
System.out.println(stringBuffer.capacity());
This will print
11
27
on console when run.
Specifying initial capacity of StringBuffer
We can specify the initial capacity of the StringBuffer object
using following method.
void ensureCapacity(int initialCapacity)
Ensures that the StringBuffer’s initial capacity would grater
than or equal to the specified initial capacity.
This method ensures the minimum capacity, but the actual capacity
may vary depending upon the capacity passed.
The new capacity of the StringBuffer is calculate using following
formula.
The new capacity of the StringBuffer is the maximum of
1) The initialCapacity argument passed and
2) ( Old capacity * 2 ) + 2
|