Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

StringBuffer is a class in Java that represents a mutable sequence of characters.

It is similar to
the String class, but it is thread-safe and can be modified without creating a new object.

StringBuffer has a number of methods that can be used to manipulate the string, including:

● append(): Appends the specified string or character to the end of the buffer.
● insert(): Inserts the specified string or character at the specified position in the buffer.
● delete(): Deletes the characters from the buffer at the specified start and end positions.
● replace(): Replaces the characters in the buffer from the specified start and end positions
with the specified string.
● reverse(): Reverses the order of the characters in the buffer.
● setLength(): Sets the length of the buffer to the specified value.
● capacity(): Returns the current capacity of the buffer.
● ensureCapacity(): Ensures that the buffer has at least the specified capacity.
● toString(): Returns a string representation of the buffer.

Here is an example of how to use some of the StringBuffer methods:

Java
StringBuffer buffer = new StringBuffer("Hello");

// Append the string " world!" to the buffer.


buffer.append(" world!");

// Insert the string "!" at the beginning of the buffer.


buffer.insert(0, "!");

// Reverse the order of the characters in the buffer.


buffer.reverse();

// Convert the buffer to a string.


String string = buffer.toString();

// Print the string to the console.


System.out.println(string);

Output:

!dlrow olleH
StringBuffer is a powerful class that can be used to manipulate strings in a variety of ways. It is
often used in applications where performance is important, as it is more efficient than the String
class for modifying strings.

You might also like