Java StringBuffer ensureCapacity() method ensures that specified minimum capacity is maintained. If the current capacity is less than the specified minimum capacity then the capacity is increased.
Syntax of ensureCapacity() method
sb.ensureCapacity(25) //if current capacity < 25 then increase capacity
Here, sb is an object of StringBuffer class.
ensureCapacity() Description
public void ensureCapacity(int min): If the current capacity of StringBuffer instance is less than the specified minimum capacity min, then the capacity of StringBuffer instance is increased using the following formula:
New Capacity = (Old Capacity*2) +2
ensureCapacity() Parameters
It takes a single parameter:
- min: It is an integer parameter, It represents the minimum capacity that needs to be maintained.
ensureCapacity() Return Value
- It does not return anything.
Example
public class JavaExample {
public static void main(String[] args) {
//StringBuffer instance using default constructor
StringBuffer sb = new StringBuffer();
//default initial capacity is 16
System.out.println("Initial Capacity: " + sb.capacity());
//If we are expecting an addition to the StringBuffer instance,
//which is greater than the default capacity 16, then we can
//increase the capacity before the operation using ensureCapacity
sb.ensureCapacity(20); // 16*2 + 2 = 34
System.out.println("New Capacity: " + sb.capacity());
sb.append("BeginnersBook.com"); //total 17 chars
System.out.println("String: " + sb);
System.out.println("Current Capacity: " + sb.capacity());
}
}
Output:
