StringBuffer ensureCapacity() method in Java with Examples
Last Updated :
28 Dec, 2022
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.
Syntax:
public void ensureCapacity(int minimumCapacity)
Parameters: This method takes one parameter minimumCapacity which is the minimum desired capacity. Return Value: This method do not return anything. Below programs demonstrate the ensureCapacity() method of StringBuffer Class Example 1:
Java
class GFG {
public static void main(String[] args)
{
StringBuffer str = new StringBuffer();
System.out.println("Before ensureCapacity "
+ "method capacity = "
+ str.capacity());
str.ensureCapacity( 18 );
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity());
}
}
|
Output:
Before ensureCapacity method capacity = 16
After ensureCapacity method capacity = 34
Example 2:
Java
class GFG {
public static void main(String[] args)
{
StringBuffer
str
= new StringBuffer("Geeks For Geeks");
System.out.println("Before ensureCapacity "
+ "method capacity = "
+ str.capacity());
str.ensureCapacity( 42 );
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity());
}
}
|
Output:
Before ensureCapacity method capacity = 31
After ensureCapacity method capacity = 64
References: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#ensureCapacity(int)
Share your thoughts in the comments
Please Login to comment...