Menu
Topics Index
...
`


Strings > StringBuffer >
Siva Nookala - 05 Apr 2016
The ensureCapacity method ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:
  • The minimumCapacity argument.
  • Twice the old capacity, plus 2.
If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.

StringBuffer Method:
MethodDescription
void ensureCapacity(int minimumCapacity)Ensures that the capacity is at least equal to the specified minimum.

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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.