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.


    void ensureCapacity(int mincap){


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 


        // 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());



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



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.