Change the default capacity of the StringBuffer Object in Java

Java 8Object Oriented ProgrammingProgramming

In order to change the default capacity of the StringBuffer Object, we use the ensureCapacity() method. When the current capacity is less than the parameter passed, then a new internal array is allocated with greater capacity.

The new capacity is the larger of the minimumCapacity argument and twice the old capacity, plus 2. If the minimum capacity is non positive, then it remains dormant and does not take any action.

Declaration-The java.lang.StringBuffer.ensureCapacity() method is declared as follows−

public void ensureCapacity(int minimumCapacity)

Let us see the working of the ensureCapacity() method

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      StringBuffer sb = new StringBuffer("Hello");
      System.out.println(sb);
      System.out.println("Original capacity : "+sb.capacity());
      sb.ensureCapacity(29); // the (twice of old capacity + 2) argument is greater
      System.out.println("New capacity : "+sb.capacity());
      System.out.println();
      StringBuffer sb1 = new StringBuffer("Hi");
      System.out.println(sb1);
      System.out.println("Original capacity : "+sb1.capacity());
      sb1.ensureCapacity(40); // the minimumCapacity argument is greater
      System.out.println("New capacity : "+sb1.capacity());
   }
}

Output

Hello
Original capacity : 21
New capacity : 44
Hi
Original capacity : 18
New capacity : 40
raja
Published on 03-Jan-2019 11:32:00
Advertisements