Last Updated : 10 Jul, 2020
The
ensureCapacity(int minimumCapacity)method of
StringBuilder classhelps us to ensures the capacity is at least equal to the specified minimumCapacity passed as the parameter to the method.
public void ensureCapacity(int minimumCapacity)Parameters:
This method accepts one parameter
minimumCapacityrepresents the minimum desired capacity you want.
Return Value:This method do not return anything. Below programs demonstrate the ensureCapacity() method of StringBuilder Class:
Example 1:In this program minimumCapacity argument which is equal to 18 is less than twice the old capacity, plus 2 which is equal to 34 then new capacity is equal to 34.
Java
// Java program to demonstrate
// the ensureCapacity() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
StringBuilder str = new StringBuilder();
// print string capacity
System.out.println("Before ensureCapacity "
+ "method capacity = "
+ str.capacity());
// apply ensureCapacity()
str.ensureCapacity(18);
// print string capacity
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity());
}
}
Output:
Before ensureCapacity method capacity = 16 After ensureCapacity method capacity = 34Example 2:
In this program minimumCapacity argument which is equal to 44 is greater than twice the old capacity, plus 2 which is equal to 34 then new capacity is equal to 34.
Java
// Java program to demonstrate
// the ensureCapacity() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
StringBuilder str = new StringBuilder();
// print string capacity
System.out.println("Before ensureCapacity"
+ " method capacity = "
+ str.capacity());
// apply ensureCapacity()
str.ensureCapacity(44);
// print string capacity
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity());
}
}
Output:
Before ensureCapacity method capacity = 16 After ensureCapacity method capacity = 44Reference: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#ensureCapacity(int)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4