JAVA - Zero to Hero / Arrays and Strings

StringBuilder and StringBuffer

πŸ“˜ 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 StringBuilder due to thread safety

  • Still 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 Rocks

Now 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

.append(), .insert(), .reverse()

Same methods as StringBuilder