Last Updated : 11 Jul, 2025
In Java, the capacity() method of StringBuilder Class is used to return the current capacity of StringBuilder object. The capacity is the amount of storage available to insert new characters.
Example 1: Here, we use the capacity() method to check the current capacity of the StringBuilder object.
Java
// Java program to demonstrate
// the capacity() Method in StringBuilder
class Geeks {
public static void main(String[] args) {
// create a StringBuilder object,
// default capacity will be 16
StringBuilder sb = new StringBuilder();
// get default capacity
int c = sb.capacity();
System.out.println("Default Capacity of StringBuilder: "
+ c);
// add the String to StringBuilder Object
sb.append("Geek");
// get capacity
c = sb.capacity();
System.out.println("StringBuilder: " + sb);
System.out.println("Current Capacity of StringBuilder: "
+ c);
}
}
Default Capacity of StringBuilder: 16 StringBuilder: Geek Current Capacity of StringBuilder: 16Syntax of StringBuilder capacity() Method
public int capacity()
Return Value: This method returns the current capacity of StringBuilder class.
Example 2: Here, we use the capacity() method with a String Passed as Parameter.
Java
// Using capacity() Method with a String Passed as Parameter
class Geeks {
public static void main(String[] args) {
// create a StringBuilder object
// with a String passed as parameter
StringBuilder sb = new StringBuilder("WelcomeGeeks");
// get capacity
int c = sb.capacity();
System.out.println("StringBuilder: " + sb);
System.out.println("Capacity of StringBuilder: "
+ c);
}
}
StringBuilder: WelcomeGeeks Capacity of StringBuilder: 28
Example 3: Here, we use the capacity() method on a null StringBuilder object. This will throw a NullPointerException.
Java
// Handling NullPointerException with
// StringBuilder capacity()
import java.io.*;
class Geeks {
public static void main(String[] args) {
// Create a null StringBuilder object
StringBuilder sb = null;
try {
int c = sb.capacity();
System.out.println("Capacity: " + c);
}
catch (NullPointerException e) {
// Handle the exception
System.out.println(
"Error: Cannot call capacity() on a null StringBuilder.");
}
}
}
Error: Cannot call capacity() on a null StringBuilder.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4