ensureCapacity() StringBuffer Example

ensureCapacity() StringBuffer Example

ensureCapacity() StringBuffer method gives guarantee the existing capacity. It behaves in two ways depending on the argument passed to the method.
  1. If the argument of the method is less than the existing capacity, then there will be no change in existing capacity (observe, sb1 in the example).
  2. If the argument is greater than the existing capacity, there will be change in the current capacity using following rule (observe, sb2 in the example).

    newcapacity = (oldcapacity*2) + 2.

What Java API says about ensureCapacity() StringBuffer:
  • public synchronized void ensureCapacity(int minCap): 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:
    a) The minimum capacity argument b) Twice the old capacity, plus 2.
    If the minCap argument is negative, no compilation error or exception is raised but no action takes place. The method does not return a value.

Following example on ensureCapacity() StringBuffer illustrates the method with 4 StringBuffer objects.

ensureCapacity() StringBuffer
Output screen on ensureCapacity() StringBuffer Example

The ensure capacity cannot be less than the old capacity.

The ensure capacity is, now in this case, twice the old capacity plus 2 (but not 30).

When ensure capacity is more than the default 16, the ensure capacity will be 50

The negative capacity value does not have any effect, just return the old existing value.

Leave a Reply

Your email address will not be published. Required fields are marked *