Home » Java programming language

Java StringBuffer void ensureCapacity(int mincap) method with Example

Java StringBuffer void ensureCapacity(int mincap) method: Here, we are going to learn about the void ensureCapacity(int mincap) method of StringBuffer class with its syntax and example.
Submitted by Preeti Jain, on June 30, 2019

StringBuffer Class void ensureCapacity(int mincap)

  • This method is available in package java.lang.StringBuffer.ensureCapacity(int mincap).
  • This method is used to ensure the capacity is at least equal to the specified argument mincap(minimum capacity).
  • If the current capacity of the StringBuffer is less than the specified argument then new space will be allocated with greater capacity.
  • The new capacity will be calculated as (2*oldcapacity+2).
  • Suppose current StringBuffer object capacity is 10 and we are allocating a new object of capacity is 26 then new space will be allocated for the newly created object.

Syntax:

    void ensureCapacity(int mincap){
    }

Parameter(s):

We pass only one object in the method of the StringBuffer i.e. minimum capacity (mincap).

Return value:

The return type of this method is void that means this method returns nothing.

Java program to demonstrate example of ensureCapacity() method

import java.lang.StringBuffer;

public class StringBufferClass {
    public static void main(String[] args) {

        StringBuffer sb = new StringBuffer(" Java supports multithreading");
        System.out.println("The value of current StringBuffer object is :" + sb);

        // Display the capacity of current stringbuffer object sb
        System.out.println("The old capacity is :" + sb.capacity());

        // Extend the capacity to the specified amount 
        // in the given stringbuffer object 

        sb.ensureCapacity(50);

        // Display new extended capacity of the stringbuffer object 

        // Return the new capacity (2*oldcapacity+2)
        System.out.println("The new capacity will be : " + sb.capacity());
    }
}

Output

D:\Programs>javac StringBufferClass.java

D:\Programs>java StringBufferClass
The value of current StringBuffer object is : Java supports multithreading
The old capacity is :45
The new capacity will be : 92



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.