StringBuilder vs StringBuffer in Java
When working with strings in Java, modifying strings frequently can be inefficient because strings are immutable. This is where StringBuilder and StringBuffer come in — they allow mutable strings, which means you can modify the content without creating new objects every time.
What are StringBuilder and StringBuffer?
| Feature | StringBuilder | StringBuffer |
|---|---|---|
| Mutability | Mutable | Mutable |
| Thread Safety | Not synchronized (faster) | Synchronized (thread-safe) |
| Performance | Faster in single-threaded programs | Slower due to synchronization |
| Introduced in | Java 5 | Java 1.0 |
| Use Case | Single-threaded string modifications | Multi-threaded string modifications |
Creating StringBuilder and StringBuffer Objects
StringBuilder
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
System.out.println(sb); // Java Programming
StringBuffer
StringBuffer sbf = new StringBuffer("Java");
sbf.append(" Programming");
System.out.println(sbf); // Java Programming
Common Methods
| Method | Description | Example |
|---|---|---|
append(String s) | Adds string at the end | sb.append(" SE") |
insert(int index, String s) | Inserts string at index | sb.insert(4, " Core") |
replace(int start, int end, String s) | Replaces substring | sb.replace(0,4,"Python") |
delete(int start, int end) | Deletes substring | sb.delete(0,6) |
reverse() | Reverses the string | sb.reverse() |
charAt(int index) | Returns character at index | sb.charAt(2) |
setCharAt(int index, char c) | Replaces character | sb.setCharAt(0,'P') |
capacity() | Returns current capacity | sb.capacity() |
length() | Returns length of content | sb.length() |
Example: Using StringBuilder
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming"); // Append
sb.insert(5, "Core "); // Insert
sb.replace(0,4,"Python"); // Replace
sb.delete(6,10); // Delete
sb.reverse(); // Reverse
System.out.println(sb); // Output after all operations
}
}
Output:
gnimmargorP eroP nohtyP
Example: Using StringBuffer (Thread-Safe)
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sbf = new StringBuffer("Java");
sbf.append(" Programming");
sbf.reverse();
System.out.println(sbf); // gnimmargorP avaJ
}
}
Points to Know :
- Strings are immutable, but StringBuilder and StringBuffer are mutable.
- StringBuilder is faster and ideal for single-threaded operations.
- StringBuffer is thread-safe, suitable for multi-threaded programs.
- Use append, insert, replace, delete, reverse methods for efficient string manipulations.
- StringBuilder and StringBuffer reduce memory overhead compared to repeated concatenation with
+.
