The ensureCapacity() method of StringBuffer class ensures the capacity to at least equal to the specified minimumCapacity.
- If the current capacity of StringBuffer < the argument minimumCapacity, then a new internal array is allocated with greater capacity.
- If the minimumCapacity argument > twice the old capacity, plus 2 then new capacity is equal to minimumCapacity else new capacity is equal to twice the old capacity, plus 2.
- If the minimumCapacity argument passed as parameter < 0, this method takes no action.
public void ensureCapacity(int minimumCapacity)
Parameters: This method takes one parameter minimumCapacity which is the minimum desired capacity.
Return Value: This method returns do not return anything.
Below programs demonstrate the ensureCapacity() method of StringBuffer Class
Before ensureCapacity method capacity = 16 After ensureCapacity method capacity = 34
Before ensureCapacity method capacity = 31 After ensureCapacity method capacity = 64
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.