DEV Community

Preethi Nandhagopal
Preethi Nandhagopal

Posted on

StringBuffer/StringBuilder

Disadvantages of String:

  1. Immutability leads to memory usage
  2. Slower performance in modifications
  3. High Garbage Collection (GC) load
  4. Less efficient for dynamic text
  5. Concatenation using + inside loops is costly

Notes:

  • Good for constant and read-only text.
  • Bad for frequent modifications → use StringBuilder / StringBuffer instead.

What is StringBuilder?

  1. StringBuilder is a mutable (changeable) sequence of characters.
  2. Unlike String (which is immutable), when you modify a StringBuilder object, it does not create a new object in memory — it updates the same object.
  3. It was introduced in Java 1.5 to provide a faster, non-synchronized alternative to StringBuffer.
  4. Faster than StringBuffer because it is not synchronized (not thread-safe).
  5. Efficient for concatenation, insertion, deletion inside loops or large text operations.
  6. Found in the package: java.lang.StringBuilder.

What is StringBuffer in Java?

  1. StringBuffer is a mutable sequence of characters (like StringBuilder).
  2. The main difference: StringBuffer is synchronized → which means thread-safe (can be safely used by multiple threads).
  3. It was introduced in Java 1.0, before StringBuilder.
  4. Because of synchronization, it is slower than StringBuilder, but safer in multithreaded programs.
  5. Found in the package: java.lang.StringBuffer.

Common Methods in StringBuilder and StringBuffer:

  • append()->Adds text at the end
  • insert()->Inserts text at given index
  • replace()->Replaces characters in range
  • delete()->Deletes characters in range
  • reverse()->Reverses the string
  • capacity()->Returns current capacity
  • length()->Returns current length
  • charAt()->Returns char at index

How StrinBuilder Difference from StringBuffer?

  • StringBuffer is synchronized (thread-safe, but slower,Multithreaded program).
  • StringBuilder is not synchronized (faster, but not thread-safe,single threaded program).

Top comments (0)