Java StringBuffer ensureCapacity() method ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity.
The new capacity is the larger of:
The new capacity is the larger of:
- The minimumCapacity argument.
- Twice the old capacity, plus 2.
Example: Example to ensure the capacity of string buffer using ensureCapacity() method.
public class EnsureCapacityExample {
public static void main(String[] args) {
StringBuffer builder = new StringBuffer();
builder.ensureCapacity(11);
System.out.println(builder.capacity());
builder.ensureCapacity(17);
System.out.println(builder.capacity());
}
}
Output:
16
34
Comments
Post a Comment