Introduction
In Java, strings are immutable, meaning once created, their values cannot be changed. To perform modifications like appending, inserting, or deleting characters efficiently, Java provides two classes: StringBuilder and StringBuffer. Both allow the creation of mutable (modifiable) strings, but they differ mainly in synchronization and performance.
Code: Example of StringBuilder and StringBuffer
public class StringBuilderVsStringBuffer {
public static void main(String[] args) {
// Using StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, ",");
sb.replace(0, 5, "Hi");
sb.delete(3, 4);
System.out.println("StringBuilder result: " + sb);
// Using StringBuffer
StringBuffer sbf = new StringBuffer("Java");
sbf.append(" Programming");
sbf.insert(4, " Language");
sbf.replace(0, 4, "Core Java");
sbf.delete(5, 9);
System.out.println("StringBuffer result: " + sbf);
}
}
Explanation of Each Code Part
1. StringBuilder Example
StringBuilder sb = new StringBuilder("Hello");
- Creates a StringBuilder object with the initial string
"Hello". - Strings created using
StringBuilderare mutable, meaning you can modify them.
sb.append(" World");
- Adds
" World"to the end of the existing string. - Result:
"Hello World"
sb.insert(5, ",");
- Inserts a comma at position 5.
- Result:
"Hello, World"
sb.replace(0, 5, "Hi");
- Replaces characters from index
0to5with"Hi". - Result:
"Hi, World"
sb.delete(3, 4);
- Deletes the character between index
3and4. - Result:
"Hi World"
2. StringBuffer Example
StringBuffer sbf = new StringBuffer("Java");
- Creates a StringBuffer object with the initial string
"Java". - Like StringBuilder, it is mutable, but synchronized, making it thread-safe.
sbf.append(" Programming");
- Adds
" Programming"to the end. - Result:
"Java Programming"
sbf.insert(4, " Language");
- Inserts
" Language"after"Java". - Result:
"Java Language Programming"
sbf.replace(0, 4, "Core Java");
- Replaces
"Java"with"Core Java". - Result:
"Core Java Language Programming"
sbf.delete(5, 9);
- Deletes characters from index
5to9. - Result:
"Core a Language Programming"
Comparison Table: StringBuilder vs StringBuffer
| Feature | StringBuilder | StringBuffer |
|---|---|---|
| Introduced In | Java 5 | Java 1.0 |
| Synchronization | Not synchronized (not thread-safe) | Synchronized (thread-safe) |
| Performance | Faster | Slower due to synchronization |
| Use Case | Single-threaded programs | Multi-threaded programs |
| Mutability | Mutable | Mutable |
| Package | java.lang | java.lang |
Conclusion
- Both StringBuilder and StringBuffer allow modification of strings without creating new objects.
- StringBuilder is faster and should be used in single-threaded applications.
- StringBuffer is thread-safe and should be used in multi-threaded environments.
- Choosing between them depends on whether your program requires synchronization or higher performance.