In this tutorial, we will discuss the Java StringBuilder ensureCapacity() method with the help of examples. This method ensures that a minimum capacity is maintained. If the current capacity is less than the specified minimum capacity then the capacity is increased.
The syntax of ensureCapacity() method is:
sb.ensureCapacity(34) //if capacity is less than 34 then increase capacity
Here, sb
is an object of StringBuilder
class.
ensureCapacity() Description
public void ensureCapacity(int min): If the current capacity of StringBuilder instance is less than the specified minimum capacity min
, then the capacity of StringBuilder instance is increased using the following formula:
New Capacity = (Old Capacity*2) +2
ensureCapacity() Parameters
The ensureCapacity() method of Java StringBuilder class takes a single parameter:
- min: This is an integer parameter that represents the minimum capacity that needs to be maintained.
ensureCapacity() Return Value
This method has void return type, which means it does not return anything.
Example of ensureCapacity() method
public class JavaExample { public static void main(String[] args) { //created a StringBuilder instance using default constructor StringBuilder sb = new StringBuilder(); //default capacity is 16 System.out.println("Initial Capacity: " + sb.capacity()); //If we are expecting an addition to the StringBuilder instance //which is greater than the default 16 then we can increase the //capacity before the operation using ensureCapacity sb.ensureCapacity(25); // 16*2 + 2 = 34 System.out.println("New Capacity: " + sb.capacity()); sb.append("Welcome to BeginnersBook"); System.out.println("String: " + sb); System.out.println("Current Capacity: " + sb.capacity()); } }
Output: