Home »
Java programming language
Java StringBuilder ensureCapacity() method with example
StringBuilder Class ensureCapacity() method: Here, we are going to learn about the ensureCapacity() method of StringBuilder Class with its syntax and example.
Submitted by Preeti Jain, on December 22, 2019
StringBuilder Class ensureCapacity() method
Syntax:
public void ensureCapacity(int min_cap);
Parameter(s):
- int min_cap – represents the minimum capacity required to perform action.
Return value:
The return type of this method is void, it returns nothing.
Example:
// Java program to demonstrate the example
// of void ensureCapacity(int min_cap)
// method of StringBuilder
public class EnsureCapacity {
public static void main(String[] args) {
// Creating an StringBuilder object
StringBuilder st_b = new StringBuilder("Java World");
// Display st_b
System.out.println("st_b = " + st_b);
// Display Current Capacity st_b i.e. 16+10
System.out.println("st_b.capacity() = " + st_b.capacity());
// By using ensureCapacity() method is to extend the capacity
// with the given amount to st_b object if required
// it returns twice the old capacity + 2 i.e.(2*st_b+2)
st_b.ensureCapacity(54);
// Display Current Capacity st_b i.e.54
System.out.println("st_b.ensureCapacity(54) = " + st_b.capacity());
}
}
Output
st_b = Java World
st_b.capacity() = 26
st_b.ensureCapacity(54) = 54