StringBuffer Class
The StringBuffer class in Java is used to represent a mutable sequence of characters. Unlike the String class, the StringBuffer class can be modified after it is created. The class provides a number of useful methods to perform various operations on strings. Here are some common methods of the StringBuffer class:
append(String str): Appends the specified string to the end of the buffer.
insert(int offset, String str): Inserts the specified string into the buffer at the specified offset.
delete(int start, int end): Deletes the characters in the buffer between the start and end indices.
reverse(): Reverses the characters in the buffer.
capacity(): Returns the current capacity of the buffer.
ensureCapacity(int minimumCapacity): Ensures that the buffer has at least the specified minimum capacity.
length(): Returns the length of the buffer.
setCharAt(int index, char ch): Sets the character at the specified index to the specified value.
substring(int start, int end): Returns a new string that is a substring of the buffer.
toString(): Returns the string representation of the buffer.
Example
public class StringBufferExample {
public static void main(String[] args) {
// Create a StringBuffer object
StringBuffer sb = new StringBuffer("Hello");
System.out.println("StringBuffer is: " + sb);
// Append a string to the StringBuffer
sb.append(" World");
System.out.println("Appended StringBuffer is: " + sb);
// Insert a string at a particular position in the StringBuffer
sb.insert(5, ", ");
System.out.println("Inserted StringBuffer is: " + sb);
// Replace a substring in the StringBuffer with another substring
sb.replace(6, 11, "Java");
System.out.println("Replaced StringBuffer is: " + sb);
// Delete a substring from the StringBuffer
sb.delete(0, 6);
System.out.println("Deleted StringBuffer is: " + sb);
// Reverse the order of the characters in the StringBuffer
sb.reverse();
System.out.println("Reversed StringBuffer is: " + sb);
}
}
