Java: StringBuffer capacity() method

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

 

capacity() method:

  • This method returns current capacity of StringBuffer 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;

Method Signature:

public int capacity();

Returns:

  • Return the current capacity

 

Examples on capacity() method:

StringBufferCapacityMethod.java

package in.bench.resources.stringbuffer.methods;

public class StringBufferCapacityMethod {

	public static void main(String[] args) {

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

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


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

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


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

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


		// 4. StringBuffer object with initial capacity 55
		StringBuffer sb4 = new StringBuffer(55);

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

Output:

1. Capacity of EMPTY StringBuffer()  : 16
2. Capacity of StringBuffer(" ")     : 17
3. Capacity of StringBuffer("Bench") : 30
4. Capacity of StringBuffer(55)      : 55

 

References:

 

Happy Coding !!
Happy Learning !!

Java: StringBuffer charAt() method
Java: StringBuffer append() method