On this document we will be showing a java example on how to use the capacity() method of StringBuilder Class. Basically the capacity() method gives the allowable number of characters this StringBuilder object can still accommodate.

Method Syntax

public int capacity()

Method Argument

Data Type Parameter Description

Method Returns

The capacity() method returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.


Requires Java 1.5 and up

Java StringBuilder capacity() Example

Below is a java code demonstrates the use of appendCodePoint() method of StringBuilder class. The example presented might be simple however it shows the behavior of the appendCodePoint() method.


import java.util.Scanner;

 * A java example source code to demonstrate
 * the use of capacity() method of StringBuilder class

public class StringBuilderCapacityExample {

	public static void main(String[] args) {

		// initialize the StringBuilder object
		StringBuilder sb = new StringBuilder("");
		System.out.println("Initial Capacity is " + sb.capacity());
		// ask for user input
		System.out.print("Please enter any input:");
		Scanner s = new Scanner(;
		// print the length of StringBuilder contents
		System.out.println("Length after user input:" + sb.length());
		System.out.println("capapcity after user input:" + sb.capacity());
		System.out.println("Current Length:" + sb.length());
		System.out.println("New Capacity:" + sb.capacity());

The above java example source code demonstrates the use of capacity() method of StringBuilder class. Initially the code displays the capacity of the StringBuilder without any characters on the buffer. And then this code takes a user input and then the program will display the new capacity. This source code is also good example in learning on how to initialize StringBuilder, and to modify the contents of the StringBuilder object.

Sample Output

Below is the sample output when you run the above example.

StringBuilder capacity() example output