Length() and capacity()
The current length of a StringBuffer can be found through the length () method, although the total allocated capacity could be found by the capacity () method. They have the subsequent common forms:
int length()
int capacity()
//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());
}
}
The output of above given program that displays how StringBuffer reserves extra space for additional manipulations:
buffer = Hello
length = 5
capacity = 21
Because sb is initialized along with the string "Hello" whenever it is created, its length is 5. Its capacity is 21 since room for 16 further characters is automatically added.