Introduction

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

Unlike String, which is immutable, StringBuilder is mutable. This means its contents can be changed after the object is created.

StringBuilder is useful when we need to perform multiple modifications to a string.

Creating a StringBuilder

A StringBuilder can be created with an initial string value.

Output:

 Hello

An empty StringBuilder can also be created.

append()

The append() method adds a value to the end of the StringBuilder.

Output:

 Hello World

We can append different types of values such as String, int, double, and char.

Output:

 Age: 20

insert()

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

Output:

 Hello Java World

Here, 6 represents the index where the new text is inserted.

replace()

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

Output:

 Hello Java

The starting index is included and 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 StringBuilder.

Output:

 olleH

length()

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

Output:

 5

charAt()

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

Output:

 e

setCharAt()

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

Output:

 Yello

StringBuilder vs String

The main difference between String and StringBuilder is mutability.

A String object cannot be changed after it is created, whereas the contents of a StringBuilder can be modified.

With StringBuilder, operations such as append(), insert(), replace(), and delete() modify the existing StringBuilder object.

Important StringBuilder 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

  • StringBuilder is used to create and modify character sequences.
  • It is mutable, unlike String.
  • append() adds content to the end.
  • insert() adds content at a specific position.
  • replace() and delete() modify existing content.
  • reverse() reverses the characters.
  • StringBuilder is useful when frequent string modifications are required.