Home »
Java programming language
Java StringBuffer int capacity() method with Example
Java StringBuffer int capacity() method: Here, we are going to learn about the int capacity() method of StringBuffer class with its syntax and example.
Submitted by Preeti Jain, on June 29, 2019
StringBuffer Class int capacity()
- This method is available in package java.lang.StringBuffer.capacity().
- This method is used to return the capacity of the StringBuffer(i.e. It is the amount of extra storage for the object that we can store beyond allocation).
- The formula to find the capacity of any StringBuffer object is 16 + "No. of characters".
Syntax:
int capacity(){
}
Parameter(s):
We don't pass any object as a parameter in the method of the StringBuffer.
Return value:
The return type of this method is int that means this method returns capacity of the StringBuffer object in number.
Java program to demonstrate example of capacity() method
import java.lang.StringBuffer;
public class StringBufferClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java is a programming language");
// use capacity() it will return the capacity(i.e 16 + 30)
// of the StringBuffer object sb.
System.out.println("The capacity of the StringBuffer object is :" + sb.capacity());
sb = new StringBuffer("10");
// use capacity() it will return the capacity(i.e. 16 + 2)
// of the another StringBuffer object sb .
System.out.println("The capacity of the another StringBuffer object is :" + sb.capacity());
sb = new StringBuffer(" ");
// use capacity() it will return the capacity(i.e. 16 + 1)
// of the another StringBuffer object sb.
System.out.println("The capacity of the another StringBuffer object is :" + sb.capacity());
}
}
Output
D:\Programs>javac StringBufferClass.java
D:\Programs>java StringBufferClass
The capacity of the StringBuffer object is :46
The capacity of the another StringBuffer object is :18
The capacity of the another StringBuffer object is :17