Introduction

StringBuffer is used to create and modify a sequence of characters.

Like StringBuilder, StringBuffer is mutable, which means its contents can be changed after the object is created.

StringBuffer is useful when a string needs to be modified multiple times, especially in situations where thread safety is required.

Creating a StringBuffer

A StringBuffer can be created with an initial string value.

Output:

 Hello

An empty StringBuffer can also be created.

append()

The append() method adds content to the end of the StringBuffer.

Output:

Hello World

We can also append numbers and other values.

Output:

 Age: 20

insert()

The insert() method adds content at a specific index.

Output:

 Hello Java World

Here, 6 represents the position where the new content is inserted.

replace()

The replace() method replaces characters within a specified range.

Output:

 Hello Java

The starting index is included, while the ending index is excluded.

delete()

The delete() method removes characters from a specified range.

Output:

 Hello

reverse()

The reverse() method reverses the characters of the StringBuffer.

Output:

 olleH

length()

The length() method returns the number of characters currently present in the StringBuffer.

Output:

5 

charAt()

The charAt() method returns the character at a particular index.

Output:

 e

setCharAt()

The setCharAt() method changes a character at a specified index.

Output:

 Yello

StringBuffer vs StringBuilder

Both StringBuffer and StringBuilder are mutable and provide similar methods.

The main difference is that StringBuffer methods are synchronized, making StringBuffer suitable for certain multi-threaded situations. StringBuilder is generally preferred when synchronization is not required because it has less synchronization overhead.

Both objects can modify their contents using methods such as append(), insert(), and delete().

Important StringBuffer Methods

  • append() – adds content at the end.
  • insert() – inserts content at a specific position.
  • replace() – replaces a range of characters.
  • delete() – removes a range of characters.
  • reverse() – reverses the content.
  • length() – returns the number of characters.
  • charAt() – returns a character at a given index.
  • setCharAt() – changes a character at a given index.

Key Takeaways

  • StringBuffer is used to create and modify character sequences.
  • It is mutable, unlike String.
  • append(), insert(), replace(), and delete() can modify its content.
  • reverse() reverses the characters.
  • StringBuffer methods are synchronized.
  • StringBuffer can be useful when working with mutable strings in multi-threaded environments.