java.lang.StringBuffer ensureCapacity(int minimumCapacity)

Description :

This java tutorial shows how to use the ensureCapacity(int minimumCapacity) method of StringBuffer class under java.lang package.

The ensureCapacity method of StringBuffer class 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)

Parameter Input :

DataType Parameter Description
int minimumCapacity the minimum desired capacity.

Compatibility Version :

Requires Java 1.0 and up

Java Code Example :

This java example source code demonstrates the use of ensureCapacity(int minimumCapacity) method of StringBuffer class. Initially the code assigns a string “java” as initial contents of the string buffer. 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.

package com.javatutorialhq.java.examples;

import java.util.Scanner;


/*
 * This example source code demonstrates the use of ensureCapacity(int minimumCapacity)
 * of StringBuffer class
 */

public class StringBufferEnsureCapacity {

	public static void main(String[] args) {
		
		
        // initialize the StringBuffer object
        StringBuffer sb = new StringBuffer("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());       
	}
}

Sample Output :

Running the capacity() method example source code of StringBuffer class will give you the following output

Contents of buffer:java
Old Capacity:20
New Capacity:42

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :