java.lang.StringBuilder ensureCapacity(int minimumCapacity)
Description
- The minimumCapacity argument.
- Twice the old capacity, plus 2.
If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.
Method Syntax
public void ensureCapacity(int minimumCapacity)
Method Argument
Data Type | Parameter | Description |
---|---|---|
int | minimumCapacity | the minimum desired capacity. |
Method Returns
The ensureCapacity(int minimumCapacity) method returns void.
Compatibility
Requires Java 1.5 and up
Java StringBuilder ensureCapacity(int minimumCapacity) Example
Below is a java code demonstrates the use of ensureCapacity(int minimumCapacity) method of StringBuilder class. The example presented might be simple however it shows the behavior of the ensureCapacity(int minimumCapacity) method.
package com.javatutorialhq.java.examples; /* * A java example source code to demonstrate * the use of ensureCapacity() method of StringBuilder class */ public class StringBuilderEnsureCapacityExample { public static void main(String[] args) { // initialize the StringBuffer object StringBuilder sb = new StringBuilder("java"); System.out.println("Contents of buffer:" + sb); System.out.println("Old Capacity:" + sb.capacity()); // increase the capacity sb.ensureCapacity(32); System.out.println("New Capacity:" + sb.capacity()); } }
The java example source code above demonstrates the use of ensureCapacity(int minimumCapacity) method of StringBuffer class. Initially the code assigns a string “java” as initial contents of this StringBuilder. The length of the string is 4. With the initial capacity of the buffer to be 16, the capacity is now 20. And then we have called the ensurecapacity method with argument value of 32, since the rule is if the argument is more than the current capacity, the capacity becomes twice the current capacity plus 2. The capacity is now (20 * 2 ) + 2 = 42.