StringBuffer in Java – Explanation with Examples
What is StringBuffer?
StringBuffer is a mutable sequence of characters in Java. That means you can modify the
content (append, insert, delete, replace) without creating new objects.
Key properties:
- Mutable
- Thread-safe (methods synchronized)
- Slower compared to StringBuilder
Why StringBuffer?
String is immutable; frequent modifications create new objects. StringBuffer avoids this
overhead.
Creating a StringBuffer:
StringBuffer sb = new StringBuffer();
StringBuffer sb2 = new StringBuffer("Hello");
Important Methods:
1. append()
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
2. insert()
StringBuffer sb = new StringBuffer("Hello World");
[Link](5, " Java");
3. replace()
StringBuffer sb = new StringBuffer("Hello World");
[Link](6, 11, "Java");
4. delete()
StringBuffer sb = new StringBuffer("Hello Java World");
[Link](5, 10);
5. reverse()
StringBuffer sb = new StringBuffer("ABCDE");
[Link]();
6. capacity()
StringBuffer sb = new StringBuffer();
[Link]();
7. length()
StringBuffer sb = new StringBuffer("Java");
[Link]();
Complete Example Program:
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link]("Append: " + sb);
[Link](5, " Java");
[Link]("Insert: " + sb);
[Link](6, 10, "Programming");
[Link]("Replace: " + sb);
[Link](5, 15);
[Link]("Delete: " + sb);
[Link]();
[Link]("Reverse: " + sb);
[Link]("Length: " + [Link]());
[Link]("Capacity: " + [Link]());
String vs StringBuffer vs StringBuilder
- String: Immutable, not thread-safe.
- StringBuffer: Mutable, thread-safe.
- StringBuilder: Mutable, fastest, not thread-safe.