String Buffer
String Buffer
A string buffer is like a String, but can be modified(mutable). At any point in time it contains
some particular sequence of characters, but the length and content of the sequence can be
changed through certain method calls.
Methods
StringBuffer provides methods to append, insert, delete, reverse, replace, and manipulate strings
in various ways. These methods allow you to modify the content of the StringBuffer object.
append(): Adds the specified string representation to the end of the StringBuffer.
insert(): Inserts the specified string representation at the specified position.
delete(): Removes a sequence of characters from the StringBuffer.
reverse(): Reverses the order of characters in the StringBuffer.
replace(): Replaces characters in the StringBuffer with new characters.
Here’s a simple example demonstrating the usage of StringBuffer
public class StringBufferExample {
public void main()
{
StringBuffer sb = new StringBuffer("Hello");
// Append
sb.append(" World");
System.out.println(sb); // Output: HelloWorld
// Insert
sb.insert(5, ", ");
System.out.println(sb); // Output: Hello,World
// Delete
sb.delete(5, 7);
System.out.println(sb); // Output: HelloWorld
// Reverse
sb.reverse();
System.out.println(sb); // Output: dlroWolleH
StringBuffer, on the other hand, is mutable, allowing strings to be modified in place without
creating a new object every time.