Introduction
Output:
HelloAn empty StringBuffer can also be created.
append()
The append() method adds content to the end of the StringBuffer.
Output:
Hello WorldWe can also append numbers and other values.
Output:
Age: 20insert()
The insert() method adds content at a specific index.
Output:
Hello Java WorldHere, 6 represents the position where the new content is inserted.
replace()
The replace() method replaces characters within a specified range.
Output:
Hello JavaThe starting index is included, while 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 StringBuffer.
Output:
olleHlength()
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:
esetCharAt()
The setCharAt() method changes a character at a specified index.
Output:
YelloStringBuffer 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.