CODE
class StringBufferDemo1
{
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("");
// returns the current capacity of the String buffer i.e. 16 + 0
System.out.println("empty capacity = " + buff.capacity());
// printing the length of empty StringBuffer
System.out.println("empty length = " + buff.length());
buff = new StringBuffer("Java"); // LINE A
// returns the current capacity of the String buffer i.e. 16 + 4
System.out.println("Java capacity = " + buff.capacity());
// printing the length of StringBuffer
System.out.println("Java length = " + buff.length());
}
}
empty capacity = 16
empty length = 0
Java capacity = 20
Java length = 4
First the capacity and length of an empty StringBuffer
is printed. Next the capacity and length of StringBuffer
containing "Java"
is printed.
StringBuffer sb = new StringBuffer(6);
System.out.println("Initial capacity : " + sb.capacity());
sb.append("Merit Campus");
System.out.println("Lenght of sb : " + sb.length());
System.out.println("StringBuffer capacity : " + sb.capacity());
6
. But when the capacity is exceeded the capacity will be increased as (initial capacity * 2 + 2), so the capacity will become 14
. StringBuffer sb = new StringBuffer(4);
System.out.println("Intial capacity : " + sb.capacity());
sb.append("Merit Campus");
System.out.println("Length of sb : " + sb.length());
System.out.println("StringBuffer capacity : " + sb.capacity());
12
.