StringBuilder and StringBuffer in Java
Introduction
StringBuilder and StringBuffer are classes in Java used to create mutable (modifiable) string objects. Unlike the immutable String class, these classes allow modification of string content without creating new objects.
Differences Between StringBuilder and StringBuffer
Feature | StringBuilder | StringBuffer |
---|---|---|
Thread Safety | Not thread-safe (faster). | Thread-safe (slower). |
Performance | Better performance in single-threaded environments. | Better suited for multi-threaded environments. |
Usage | Use when thread safety is not required. | Use when thread safety is required. |
1. Using StringBuilder
Example: Appending Strings
public class StringBuilderExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); System.out.println("StringBuilder result: " + sb.toString()); // Output: Hello World } }
Example: Inserting and Reversing
public class StringBuilderAdvancedExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Java"); sb.insert(4, " Programming"); System.out.println("After insertion: " + sb.toString()); // Output: Java Programming sb.reverse(); System.out.println("After reversing: " + sb.toString()); // Output: gnimmargorP avaJ } }
2. Using StringBuffer
Example: Appending Strings
public class StringBufferExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println("StringBuffer result: " + sb.toString()); // Output: Hello World } }
Example: Deleting and Replacing
public class StringBufferAdvancedExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello Java"); sb.delete(5, 10); System.out.println("After deletion: " + sb.toString()); // Output: Hello sb.replace(0, 5, "Hi"); System.out.println("After replacement: " + sb.toString()); // Output: Hi } }
3. Conclusion
Both StringBuilder and StringBuffer are powerful tools for handling mutable strings in Java:
- Use StringBuilder when you do not need thread safety.
- Use StringBuffer when thread safety is required.
Understanding the differences and use cases of these classes can help optimize your code.