StringBuilder is a mutable class in Java that is used to create and manipulate strings efficiently. It’s part of the java.lang package and is available since Java 1.5.
🧱 Why do we need StringBuilder?
Problem with String (Immutable)
In Java, String is immutable, meaning every time you modify a String (like concatenation), a new string object is created.
This creates unnecessary objects in memory, which can be slow if you’re performing a lot of string manipulations (loops, repeated appends, etc.).
String str = "Hello";
str = str + " World"; // Creates a new String object — inefficient in loops
StringBuilder — The Solution
StringBuilder is mutable, meaning it can change its content directly without creating new objects.
It’s faster for frequent modifications (appending, inserting, deleting, replacing).
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the existing object (efficient)
📊 Key Differences
Feature
String
StringBuilder
Mutability
Immutable
Mutable
Performance (modification)
Slower (creates new objects)
Faster (modifies in-place)
Thread-safety
Thread-safe (immutable = safe)
Not thread-safe
Usage
When immutability is important (e.g., keys in maps)
When you need heavy modification (e.g., loops, text processing)