Java StringBuffer ensureCapacity() Method

ensureCapacity(int minCapacity):

Java StringBuffer ensureCapacity ensures that the capacity is at least equal to the specified minimum.

Syntax:

public void ensureCapacity(int minCapacity)

Note:

  • If the current capacity is greater than the argument there will be no change in the current capacity.
  • If the current capacity is less than the argument there will be a change in the current capacity using the below rule.
    newcapacity = (oldcapacity*2) + 2

Example:

class TestStringBuffer{
    StringBuffer sb = new StringBuffer();

    public void ensureCapacityTest(){
        //default capacity.
        System.out.println(sb.capacity());
        
        sb.append("Hello ");
        //current capacity 16.
        System.out.println(sb.capacity());
        
        sb.append("w3schools.blog");
        //current capacity (16*2)+2=34 i.e (oldcapacity*2)+2.  
        System.out.println(sb.capacity());
        
        sb.ensureCapacity(10);
        //now no change in capacity because 
                //minimum is already set to 34. 
        System.out.println(sb.capacity());  
          
        sb.ensureCapacity(50);
        //now (34*2)+2 = 70 as 50 is greater than 34.
        System.out.println(sb.capacity());
    }
}

public class StringBufferEnsureCapacityExample {
    public static void main(String args[]){
        //creating TestStringBuffer object
        TestStringBuffer obj = new TestStringBuffer();
        
        //method call
        obj.ensureCapacityTest();
    }
}

Output

16 
34 
34 
70