Set the capacity value for a StringBuffer object in Java


The capacity() method returns the current capacity. It is a part of the StringBuffer. It is the quantity of storage present for recently inserted characters, after which an allocation occurs.

Declaration - The capacity() method is declared in the java.lang.StringBuffer class as follows −

public int capacity()

The capacity of a StringBuffer object can be set by inserting the value to be set while instantiating the StringBuffer class.

Let us see an example program showing how the capacity value can be set.

Example

 Live Demo

import java.lang.*;
public class Example {
   public static void main(String[] args) {
      StringBuffer b = new StringBuffer(100);
      System.out.println("Capacity for the StringBuffer Object = " + b.capacity());
      b = new StringBuffer(" ");
      // returns the current capacity of the String buffer which is 16 + 1
      System.out.println("Capacity for the StringBuffer Object = " + b.capacity());
   }
}

Output

Capacity for the StringBuffer Object = 100
Capacity for the StringBuffer Object = 17

Updated on: 26-Jun-2020

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements