java.lang.StringBuilder ensureCapacity(int minimumCapacity)

Description

On this document we will be showing a java example on how to use the ensureCapacity(int minimumCapacity) method of StringBuilder Class. Basically the 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.

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.

Sample Output

Below is the sample output when you run the above example.

StringBuilder ensureCapacity() example output