Java StringBuffer Tutorial
Introduction to StringBuffer in Java
In Java, strings are immutable, meaning once created, their values cannot be changed. To handle mutable strings efficiently, Java provides the StringBuffer class.
StringBuffer allows you to create strings that can be modified after creation without creating new objects, which improves performance in certain scenarios.
Mutable strings for efficient string manipulation.
What is StringBuffer?
StringBuffer is a thread-safe, mutable sequence of characters. Unlike String, which is immutable, StringBuffer objects can be modified after they are created.
It is part of the java.lang package and provides methods to append, insert, delete, and reverse characters efficiently.
- Mutable sequence of characters
- Thread-safe due to synchronized methods
- Part of java.lang package
- Useful for frequent modifications of strings
Creating and Using StringBuffer
You can create a StringBuffer object using its constructors. The most common ways are to create an empty buffer or initialize it with a string.
Once created, you can use various methods to modify the content of the StringBuffer.
- StringBuffer() - creates an empty buffer with default capacity
- StringBuffer(String str) - creates a buffer initialized with the specified string
Common StringBuffer Methods
StringBuffer provides several methods to manipulate the character sequence efficiently.
- append(String s) - adds the specified string to the end
- insert(int offset, String s) - inserts a string at the specified position
- delete(int start, int end) - removes characters from start to end index
- replace(int start, int end, String s) - replaces characters between start and end with the specified string
- reverse() - reverses the sequence of characters
- toString() - converts the StringBuffer to a String
StringBuffer vs StringBuilder
Both StringBuffer and StringBuilder provide mutable sequences of characters, but they differ in thread safety and performance.
StringBuffer is synchronized, making it thread-safe but slower, while StringBuilder is not synchronized and faster but not thread-safe.
- Use StringBuffer when thread safety is required.
- Use StringBuilder for better performance in single-threaded environments.
| Feature | StringBuffer | StringBuilder |
|---|---|---|
| Thread Safety | Synchronized (Thread-safe) | Not synchronized (Not thread-safe) |
| Performance | Slower due to synchronization | Faster without synchronization |
| Introduced in | Java 1.0 | Java 5 |
When to Use StringBuffer
StringBuffer is ideal when you need to modify strings frequently in a multi-threaded environment.
It helps avoid creating multiple immutable String objects, thus improving memory and performance.
- Building strings dynamically in multi-threaded applications
- When thread safety is a concern
- When you need to perform many modifications on strings
Examples
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
sb.insert(5, ",");
sb.replace(6, 11, " Java");
sb.delete(11, 12);
System.out.println(sb.toString());
}
}This example demonstrates creating a StringBuffer, appending text, inserting a comma, replacing a substring, deleting a character, and printing the final string.
Best Practices
- Use StringBuffer when thread safety is required for mutable strings.
- Prefer StringBuilder in single-threaded scenarios for better performance.
- Avoid unnecessary conversions between String and StringBuffer to reduce overhead.
- Use appropriate initial capacity to minimize resizing overhead.
Common Mistakes
- Using StringBuffer unnecessarily in single-threaded applications instead of StringBuilder.
- Not converting StringBuffer to String when needed for APIs that require String.
- Assuming StringBuffer is immutable like String.
- Ignoring initial capacity leading to frequent resizing and performance hits.
Hands-on Exercise
Modify a String using StringBuffer
Create a StringBuffer initialized with "Java". Append " Programming", insert " Language" after "Java", then reverse the entire string and print the result.
Expected output: gnimmargorP egaugnaL avaJ
Hint: Use append(), insert(), and reverse() methods of StringBuffer.
Interview Questions
What is the difference between String, StringBuffer, and StringBuilder in Java?
InterviewString is immutable, meaning its value cannot be changed after creation. StringBuffer and StringBuilder are mutable sequences of characters. StringBuffer is synchronized and thread-safe, while StringBuilder is not synchronized and faster but not thread-safe.
When should you use StringBuffer over StringBuilder?
InterviewUse StringBuffer when you need thread safety in a multi-threaded environment. For single-threaded scenarios, StringBuilder is preferred for better performance.
Summary
StringBuffer is a mutable, thread-safe sequence of characters in Java, useful for frequent string modifications in multi-threaded contexts.
It provides various methods to efficiently manipulate strings without creating new objects.
Understanding when to use StringBuffer versus StringBuilder is important for writing efficient and safe Java code.
FAQ
Is StringBuffer thread-safe?
Yes, StringBuffer is synchronized, making it thread-safe for use in multi-threaded environments.
Can I convert a StringBuffer to a String?
Yes, you can convert a StringBuffer to a String using the toString() method.
Why is String immutable in Java?
String is immutable to provide security, synchronization, and performance benefits such as caching hash codes.
