Java.Core.What is StringBuilder?

🚀 What is StringBuilder?

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

FeatureStringStringBuilder
MutabilityImmutableMutable
Performance (modification)Slower (creates new objects)Faster (modifies in-place)
Thread-safetyThread-safe (immutable = safe)Not thread-safe
UsageWhen immutability is important (e.g., keys in maps)When you need heavy modification (e.g., loops, text processing)

🏎️ How StringBuilder Works

Common methods:

MethodDescription
append()Add to the end
insert()Insert at a specific position
replace()Replace characters in a range
delete()Remove characters in a range
reverse()Reverse the string
toString()Convert back to String

Example:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, ",");
sb.replace(6, 11, "Java");
sb.reverse();
System.out.println(sb);  // avaJ ,olleH

🔐 What about StringBuffer?

  • StringBuffer is almost the same as StringBuilder, but it’s thread-safe (synchronized).
  • StringBuilder is faster because it’s not synchronized.
  • Use StringBuilder in single-threaded code (most common).
  • Use StringBuffer only if multiple threads need to modify the same string (rare nowadays, since strings are often thread-local).

📚 Summary

ClassMutableThread-safeSpeed
String❌ No✅ Yes🚶 Slow (for modifications)
StringBuilder✅ Yes❌ No🚀 Fast
StringBuffer✅ Yes✅ Yes🐢 Slower (due to synchronization)

💡 When to use which?

Use CaseRecommendation
Simple, fixed string (constants, messages)String
Frequent modifications (loops, file parsing, JSON building)StringBuilder
Frequent modifications + shared between threadsStringBuffer (but better design is often to avoid shared state)
This entry was posted in Без рубрики. Bookmark the permalink.