Get the capacity of the StringBuffer Object in Java

Java 8Object Oriented ProgrammingProgramming

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.


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


Capacity for the StringBuffer Object = 21
Updated on 26-Jun-2020 15:13:15