Get the capacity of the StringBuffer Object in Java


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

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

public int capacity()

Let us see an example program showing how to get the capacity of the StringBuffer Object.

Example

 Live Demo

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

Output

Capacity for the StringBuffer Object = 21

Updated on: 26-Jun-2020

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements