The capacity()
method of the StringBuffer
class in Java is used to return buffer capacity. By default, a string buffer has a 16 character capacity. By calling this method, we can calculate its current capacity.
Capacity refers to the total number of character storage size in a string buffer.
int capacity()
N/A
: It does not take any argument value.
int
: It returns the available size as integer count.
In Java, a primitive data-type integer is 32-bits. The range is from
-2147483648
to2147483647
.
The code below illustrates the use of the capacity()
method of StringBuffer
class. In line 7, sb1
is declared with a default size of 16
. Whereas in line 11, sb2
is declared with a default value of "Welcome to"
. The total size will be 16+10=26.
// importing StringBuffer Classimport java.lang.StringBuffer;// driver classclass EdPresso {// main method starting herepublic static void main( String args[] ) {StringBuffer sb1 = new StringBuffer();//printing default capacity of string bufferSystem.out.println("sb1: default capacity: " + sb1.capacity());// current size 16+10 = 26StringBuffer sb2 = new StringBuffer("Welcome to");System.out.println("sb2: After declaration capacity: " + sb2.capacity());sb2.append(" Educative");// printing sb2 contentSystem.out.println(sb2);// Againg printing sb2 contentSystem.out.println("sb2:Current capacity after addition: " + sb2.capacity());}}