Java StringBuilder & StringBuffer Methods - Descriptions & Examples
Java StringBuilder / StringBuffer Methods - Descriptions & Examples
1. append(String str)
- Description: Appends the specified string to the end.
- Example:
sb.append("Hello");
2. insert(int offset, String str)
- Description: Inserts the string at the specified position.
- Example:
sb.insert(1, "Java");
3. replace(int start, int end, String str)
- Description: Replaces characters from start to end with the specified string.
- Example:
sb.replace(0, 4, "Hi");
4. delete(int start, int end)
- Description: Deletes characters from start to end.
- Example:
sb.delete(0, 2);
5. reverse()
- Description: Reverses the characters in the sequence.
- Example:
sb.reverse();
6. capacity()
- Description: Returns the current capacity of the buffer.
- Example:
int cap = sb.capacity();
7. ensureCapacity(int minimumCapacity)
- Description: Ensures that the capacity is at least equal to the specified minimum.
- Example:
sb.ensureCapacity(50);
8. setCharAt(int index, char ch)
- Description: Sets the character at the specified index.
- Example:
sb.setCharAt(0, 'A');
9. charAt(int index)
- Description: Returns the character at the specified index.
- Example:
char ch = sb.charAt(1);
10. length()
- Description: Returns the length (character count).
- Example:
int len = sb.length();
11. substring(int start)
- Description: Returns a substring starting from the given index.
- Example:
String sub = sb.substring(2);
12. substring(int start, int end)
- Description: Returns a substring from start to end.
- Example:
String sub = sb.substring(1, 4);
13. deleteCharAt(int index)
- Description: Removes the char at the specified index.
- Example:
sb.deleteCharAt(0);