Menu
Topics Index
...
`

StringBufferDemo2 - Java Example Program


StringBufferDemo2
class StringBufferDemo2
{
    public static void main(String[] args) {
    
        StringBuffer sb = new StringBuffer("Java");
        System.out.println("Buffer = " + sb);
    
        // current capacity of string buffer is 16 + 4
        System.out.println("Old Capacity = " + sb.capacity());
    
        // capacity remains same
        sb.ensureCapacity(19); // LINE A
        System.out.println("New Capacity1 = " + sb.capacity());
    
        // capacity is twice plus 2
        sb.ensureCapacity(21); // LINE B
        System.out.println("New Capacity2 = " + sb.capacity());
    
        // capacity increased to the specified amount
        sb.ensureCapacity(100); // LINE C
        System.out.println("New Capacity3 = " + sb.capacity());
    
    }
}
OUTPUT

Buffer = Java
Old Capacity = 20
New Capacity1 = 20
New Capacity2 = 42
New Capacity3 = 100

DESCRIPTION

First the capacity of StringBuffer containing "Java" is printed. At LINE A the capacity of it remains same as the value passed on to ensureCapacity() is less than the older capacity. At LINE B the capacity of it is increased as the value passed on to ensureCapacity() is greater than the older capacity. At LINE C, the capacity of it is increased as needed to the specified amount as it's greater than twice the capacity plus 2.

THINGS TO TRY
  • Try taking "Merit Campus" into the StringBuffer and print the capacity before and after ensuring a capacity of 26 at LINE A.
  • Try taking "Merit Campus" into the StringBuffer and print the capacity before and after ensuring a capacity of 30 at LINE B.
  • Try taking "Merit Campus" into the StringBuffer and print the capacity before and after ensuring a capacity of 100 at LINE C.

© meritcampus 2019

All Rights Reserved.

Open In App