In this article, we will discuss StringBuffer’s capacity() method which returns the current capacity
1. StringBuffer’s 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;
1.1 Method Signature:
public int capacity();
1.2 Returns:
- Return the current capacity
2. 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
Related Articles:
- StringBuffer class
- StringBuffer append() method (13)
- StringBuffer capacity() method
- StringBuffer charAt(int index) method
- StringBuffer delete(int start, int end) method
- StringBuffer deleteCharAt(int index) method
- StringBuffer ensureCapacity(int minimumCapacity) method
- StringBuffer indexOf() method (2)
- StringBuffer insert() method (12)
- StringBuffer lastIndexOf() method (2)
- StringBuffer length() method
- StringBuffer replace(int start, int end, String str) method
- StringBuffer reverse() method
- StringBuffer substring(int start, int end) method
References:
- https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
- https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
- https://docs.oracle.com/javase/tutorial/java/data/strings.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
Happy Coding !!
Happy Learning !!