π What is StringBuilder in Java?
StringBuilder is a class in Java used to create mutable (changeable) strings.
Unlike the String class (which is immutable, meaning it cannot be changed once created), StringBuilder allows you to modify the contents of the string without creating a new object every time.
π§ Why Use StringBuilder?
Faster than String when doing repeated modifications like appending, deleting, or inserting
Saves memory and improves performance
Ideal for single-threaded programs
βοΈ Example Code
public class Example {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);
}
}Hello Worldπ What is StringBuffer in Java?
StringBuffer is also a class in Java used to create mutable strings, just like StringBuilder.
The main difference is that StringBuffer is thread-safe β which means it can be safely used in programs where multiple threads access and modify the string. **(We will learn about threading in further modules)
π§ Why Use StringBuffer?
Used in multi-threaded environments
All methods are synchronized, so only one thread can access them at a time
Slightly slower than
StringBuilderdue to thread safetyStill supports modification without creating new objects
βοΈ Example Code
public class Example {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.insert(4, " Rocks");
System.out.println(sb);
}
}Java RocksNow you have both:
β
StringBuilderβ for fast, single-threaded useβ
StringBufferβ for safe, multi-threaded use
π Summary (with Example Keywords):
Feature | StringBuilder | StringBuffer |
|---|---|---|
Mutable | β Yes | β Yes |
Thread-safe | β No | β Yes |
Faster (single-threaded) | β Yes | β Slightly slower (synchronized) |
Example Methods |
| Same methods as |