Java StringBuilder ensureCapacity() Method Example

Java StringBuilder ensureCapacity(int minimumCapacity) method ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:
  • The minimumCapacity argument.
  • Twice the old capacity, plus 2.

Java StringBuilder ensureCapacity() Method Example

Example to ensure the capacity of string buffer using ensureCapacity() method.
public class EnsureCapacityExample {
    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder();
        builder.ensureCapacity(11);
        System.out.println(builder.capacity());
    }
}
Output:
16

Reference



Comments