Java – StringBuilder capacity() method

In this article, we will discuss StringBuilder’s capacity() method which returns the current capacity

1. StringBuilder’s capacity() method :

  • This method returns current capacity of StringBuilder object
  • Capacity is the amount of storage available to insert new characters
    • Note: default capacity is 16
  • Beyond capacity limit, a new allocation occurs based on below calculation
    • Formula: New capacity = (old capacity * 2) + 2;

1.1 Method Signature:

public int capacity();

1.2 Returns:

  • Returns current capacity

2. Examples on capacity() method:

StringBuilderCapacityMethod.java

package in.bench.resources.stringbuilder.methods;

public class StringBuilderCapacityMethod {

	public static void main(String[] args) {

		// 1. empty StringBuilder object
		StringBuilder sb1 = new StringBuilder();

		// capacity - default 16
		System.out.println("1. Capacity of "
				+ "EMPTY StringBuilder()   		: "
				+ sb1.capacity());

		// 2. empty StringBuilder object with single space
		StringBuilder sb2 = new StringBuilder(" ");

		// capacity - 16 + 1 = 17
		System.out.println("2. Capacity of "
				+ "StringBuilder(\" \")     		: "
				+ sb2.capacity());

		// 3. StringBuilder object with initialized string
		StringBuilder sb3 = new StringBuilder("BenchResources");

		// capacity - 16 + 14 = 30
		System.out.println("3. Capacity of "
				+ "StringBuilder(\"BenchResources\") 	: "
				+ sb3.capacity());

		// 4. StringBuilder object with initial capacity 65
		StringBuilder sb4 = new StringBuilder(65);

		// capacity - 55
		System.out.println("4. Capacity of "
				+ "StringBuilder(65)      		: "
				+ sb4.capacity());
	}
}

Output:

1. Capacity of EMPTY StringBuilder()   		: 16
2. Capacity of StringBuilder(" ")     		: 17
3. Capacity of StringBuilder("BenchResources") 	: 30
4. Capacity of StringBuilder(65)      		: 65

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java - StringBuilder charAt() method
Java - StringBuilder append() method