Before going into the table of ensureCapacity() vs setLength() vs trimToSize(), it is advised to refer the programs at:
- ensureCapacity() StringBuffer Example
- setLength() StringBuffer Example
- trimToSize() StringBuffer Example
Following terminology is to be remembered:
- Length: It is the number of characters present in the buffer (which generally be same or less than the capacity).
- 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()
|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()".