ensureCapacity() vs setLength() vs trimToSize() StringBuffer


Before going into the table of ensureCapacity() vs setLength() vs trimToSize(), it is advised to refer the programs at:
  1. ensureCapacity() StringBuffer Example
  2. setLength() StringBuffer Example
  3. trimToSize() StringBuffer Example

Following terminology is to be remembered:

  1. Length: It is the number of characters present in the buffer (which generally be same or less than the capacity).
  2. Capacity: It is the storing capacity of the StringBuffer object (which will be more than the length or same).
Table showing the differences ensureCapacity() vs setLength() vs trimToSize()
Property ensureCapacity() setLength() trimToSize()
Capacity Buffer capacity is set irrespective of length Length (number of characters) is set. Buffer may be more than length Extra buffer is deleted than required to store the characters
Length Capacity cannot be less than length Capacity can be more than length Capacity and length will be same
Usage Used to set extra buffer Used to set the number of characters Used to save buffer memory
Example Program How to use ensureCapacity()? How to use setLength()? How to use trimToSize()?

Pass your comments and suggestions on this tutorial "ensureCapacity() vs setLength() vs trimToSize()".

Leave a Comment

Your email address will not be published.