Java StringBuilder capacity() method returns the current capacity of StringBuilder object. In this tutorial, we will discuss the capacity() method in detail with the help of examples.
StringBuilder sb = new StringBuilder(); //default capacity 16 StringBuilder sb = new StringBuilder(34); //capacity 34
Syntax of capacity() method:
int cp = sb.capacity() //returns the capacity of sb
Here, sb is an object of StringBuilder class.
capacity() Description
public int capacity(): Returns the current capacity. If the current capacity is exhausted by adding new elements, the capacity is automatically increased using the following formula:
New Capacity = (Old Capacity*2)+2
capacity() Parameters
- It does not take any parameter.
capacity() Return Value
- It returns an integer value, which represents the current capacity of StringBuilder object.
Example 1: Capacity for various sequences
class JavaExample{
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("TEST STRING");
/* Capacity of newly created StringBuilder instance
* = length of string "TEST STRING" + 16
* i.e 11+16 =27
*/
System.out.println("Case1: Capacity: "+sb.capacity());
StringBuilder sb2 = new StringBuilder(); //default 16
System.out.println("Case2: Capacity: "+sb2.capacity());
StringBuilder sb3 = new StringBuilder("ABC");
/* Capacity = length of String "ABC"+ default capacity
* i.e 3+16 =19
*/
System.out.println("Case3: Capacity: "+sb3.capacity());
}
}
Output:

Example 2: Capacity Increase when limit exhausted
class JavaExample{
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println("Capacity: "+sb.capacity()); //default 16
sb.append("Text"); // capacity is not exhausted
System.out.println("Capacity: "+sb.capacity());
//appending 15 chars in the sequence
//so sequence now has 19 char, which cant be adjusted
// in default capacity so capacity is increased
// new capacity = (16*2)+2 = 34
sb.append("123456789101112");
System.out.println("Capacity: "+sb.capacity());
}
}
Output:

Example 3: Free extra capacity
To free up the capacity, we have used trimToSize() method.
class JavaExample{
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Welcome to BeginnersBook.com"); //16*2+2 = 34
System.out.println("Capacity: "+sb.capacity()); //34
//we appended 28 characters, capacity is increased from 16 to 34
//if we want to trim extra capacity and free memory
sb.trimToSize();
System.out.println("Capacity after trim: "+sb.capacity());
}
}
Output:

Leave a Reply