Description
public int capacity()
: Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
Example
This example demonstrate the use of capacity() method of StringBuilder
class.
import java.lang.StringBuilder; class StringBuilderCapacity{ 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(); System.out.println("Case2: Capacity: "+sb2.capacity()); StringBuilder sb3 = new StringBuilder("ABC"); /* Capacity = length of String "ABC"=16 * i.e 3+16 =19 */ System.out.println("Case3: Capacity: "+sb3.capacity()); } }
Output:
Case1: Capacity: 27 Case2: Capacity: 16 Case3: Capacity: 19
Leave a Reply