Introduction
Output:
HelloAn empty StringBuilder can also be created.
append()
The append() method adds a value to the end of the StringBuilder.
Output:
Hello WorldWe can append different types of values such as String, int, double, and char.
Output:
Age: 20insert()
The insert() method adds a value at a specific index.
Output:
Hello Java WorldHere, 6 represents the index where the new text is inserted.
replace()
The replace() method replaces characters within a specified range.
Output:
Hello JavaThe starting index is included and the ending index is excluded.
delete()
The delete() method removes characters from a specified range.
Output:
Helloreverse()
The reverse() method reverses the characters of the StringBuilder.
Output:
olleHlength()
The length() method returns the number of characters present in the StringBuilder.
Output:
5charAt()
The charAt() method returns the character at a particular index.
Output:
esetCharAt()
The setCharAt() method changes the character at a specified index.
Output:
YelloStringBuilder 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.