C

Core Java tutorial for beginners

Clean • Professional

Core Java Strings – StringBuilder vs StringBuffer Explained

3 minute

StringBuilder vs StringBuffer in Java

When working with strings in Java, modifying strings frequently can be inefficient because strings are immutable. This is where StringBuilder and StringBuffer come in — they allow mutable strings, which means you can modify the content without creating new objects every time.


What are StringBuilder and StringBuffer?

FeatureStringBuilderStringBuffer
MutabilityMutableMutable
Thread SafetyNot synchronized (faster)Synchronized (thread-safe)
PerformanceFaster in single-threaded programsSlower due to synchronization
Introduced inJava 5Java 1.0
Use CaseSingle-threaded string modificationsMulti-threaded string modifications

Creating StringBuilder and StringBuffer Objects

StringBuilder

StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
System.out.println(sb); // Java Programming

StringBuffer

StringBuffer sbf = new StringBuffer("Java");
sbf.append(" Programming");
System.out.println(sbf); // Java Programming

Common Methods

MethodDescriptionExample
append(String s)Adds string at the endsb.append(" SE")
insert(int index, String s)Inserts string at indexsb.insert(4, " Core")
replace(int start, int end, String s)Replaces substringsb.replace(0,4,"Python")
delete(int start, int end)Deletes substringsb.delete(0,6)
reverse()Reverses the stringsb.reverse()
charAt(int index)Returns character at indexsb.charAt(2)
setCharAt(int index, char c)Replaces charactersb.setCharAt(0,'P')
capacity()Returns current capacitysb.capacity()
length()Returns length of contentsb.length()

Example: Using StringBuilder

public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java");

        sb.append(" Programming");      // Append
        sb.insert(5, "Core ");          // Insert
        sb.replace(0,4,"Python");       // Replace
        sb.delete(6,10);                // Delete
        sb.reverse();                   // Reverse

        System.out.println(sb);          // Output after all operations
    }
}

Output:

gnimmargorP eroP nohtyP

Example: Using StringBuffer (Thread-Safe)

public class StringBufferDemo {
    public static void main(String[] args) {
        StringBuffer sbf = new StringBuffer("Java");
        sbf.append(" Programming");
        sbf.reverse();
        System.out.println(sbf); // gnimmargorP avaJ
    }
}

Points to Know :

  1. Strings are immutable, but StringBuilder and StringBuffer are mutable.
  2. StringBuilder is faster and ideal for single-threaded operations.
  3. StringBuffer is thread-safe, suitable for multi-threaded programs.
  4. Use append, insert, replace, delete, reverse methods for efficient string manipulations.
  5. StringBuilder and StringBuffer reduce memory overhead compared to repeated concatenation with +.

🏆 Top 5 Java Interview Questions - StringBuilder & StringBuffer

1. Difference between String, StringBuilder, and StringBuffer

Answer:

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread-safetyN/ANot synchronizedSynchronized (thread-safe)
PerformanceSlower for frequent modificationFasterSlower than StringBuilder due to synchronization
UsageStore constant/unchanging stringsBuild or modify strings frequentlyBuild/modify strings in multithreaded context
ExampleString s = "Hello";StringBuilder sb = new StringBuilder("Hello");StringBuffer sbf = new StringBuffer("Hello");

2. When should you use StringBuilder vs StringBuffer?

Answer:

  • StringBuilder: Use when modifying strings frequently in a single-threaded environment.
  • StringBuffer: Use when modifying strings in a multithreaded environment, as it is thread-safe.

3. Why are StringBuilder and StringBuffer mutable while String is not?

Answer:

  • String objects are immutable for security, caching, and memory optimization.
  • StringBuilder/StringBuffer are mutable because they allow in-place modifications without creating new objects, which improves performance when modifying strings repeatedly.

4. Name 5 commonly used methods in StringBuilder/StringBuffer

Answer:

MethodDescriptionExample
append()Adds text at the endsb.append("World");
insert()Inserts text at a specific indexsb.insert(5, " Java");
delete()Deletes characters from start to end indexsb.delete(0, 5);
reverse()Reverses the stringsb.reverse();
replace()Replaces characters between indexessb.replace(0, 5, "Hi");

5. What is the difference in thread-safety between StringBuilder and StringBuffer?

Answer:

  • StringBuilder: Not synchronized → not thread-safe, faster in single-threaded code.
  • StringBuffer: Synchronized → thread-safe, suitable for multithreaded applications.

Example:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Safe in single thread

StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World"); // Thread-safe in multithreaded code

 

Article 0 of 0