Java.lang.StringBuffer.ensureCapacity() Method

Advertisements


Description

The java.lang.StringBuffer.ensureCapacity() 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.

Declaration

Following is the declaration for java.lang.StringBuffer.ensureCapacity() method

public void ensureCapacity(int minimumCapacity)

Parameters

  • minimumCapacity -- This is the minimum desired capacity.

Return Value

This method does not return any value.

Exception

  • NA

Example

The following example shows the usage of java.lang.StringBuffer.ensureCapacity() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBufferDemo {

  public static void main(String[] args) {
  
    StringBuffer buff1 = new StringBuffer("tuts point");
    System.out.println("buffer1 = " + buff1);

    // returns the current capacity of the string buffer 1
    System.out.println("Old Capacity = " + buff1.capacity());
    /* increases the capacity, as needed, to the specified amount in the 
    given string buffer object */
    // returns twice the capacity plus 2
    buff1.ensureCapacity(28);
    System.out.println("New Capacity = " + buff1.capacity());

    StringBuffer buff2 = new StringBuffer("compile online");
    System.out.println("buffer2 = " + buff2);
    // returns the current capacity of string buffer 2
    System.out.println("Old Capacity = " + buff2.capacity());
    /* returns the old capacity as the capacity ensured is less than the
    old capacity */
    buff2.ensureCapacity(29);
    System.out.println("New Capacity = " + buff2.capacity());
  }
}

Let us compile and run the above program, this will produce the following result:

buffer1 = tuts point
Old Capacity = 26
New Capacity = 54
buffer2 = compile online
Old Capacity = 30
New Capacity = 30



Advertisements
Advertisements