Java — Important Methods of StringBuffer Class | Code Factory

Index Page : Link

Donate : Link

1. public int length()

- Returns the length (character count).

2. 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.

3. public char charAt(int index)

- Returns the char value in this sequence at the specified index. The first char value is at index 0, the next at index 1, and so on, as in array indexing.

- IndexOutOfBoundsException - if index is negative or greater than or equal to length().

4. public void setCharAt(int index, char ch)

- The character at the specified index is set to ch. This sequence is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.

- IndexOutOfBoundsException - if index is negative or greater than or equal to length().

5. append

- StringBuffer contains multiple methods with append name.

6. insert

- StringBuffer contains multiple methods with insert name.

7. public StringBuffer delete(int start, int end)

- Removes the characters in a substring of this sequence. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made.

- StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than end.

8. public StringBuffer deleteCharAt(int index)

- Removes the char at the specified position in this sequence. This sequence is shortened by one char.

- StringIndexOutOfBoundsException - if the index is negative or greater than or equal to length().

9. public StringBuffer reverse()

- Causes this character sequence to be replaced by the reverse of the sequence.

10. public void setLength(int newLength)

- Sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument.

- IndexOutOfBoundsException - if the newLength argument is negative.

11. public void ensureCapacity(int minimumCapacity)

- 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.

12. public void trimToSize()

- Attempts to reduce storage used for the character sequence. If the buffer is larger than necessary to hold its current sequence of characters, then it may be resized to become more space efficient.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store