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 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);
}
}
Output
Default Capacity of StringBuilder: 16 StringBuilder: Geek Current Capacity of StringBuilder: 16
Syntax 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.
// 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);
}
}
Output
StringBuilder: WelcomeGeeks Capacity of StringBuilder: 28
Example 3: Here, we use the capacity() method on a null StringBuilder object. This will throw a NullPointerException.
// 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.");
}
}
}
Output
Error: Cannot call capacity() on a null StringBuilder.