DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-84 Understanding String, StringBuffer, and StringBuilder in Java

1. String in Java

  • Immutable: Once created, the value of a String object cannot be changed.
  • Thread-safety: Since it’s immutable, it is inherently thread-safe.
  • Speed: Slower when doing multiple modifications (because each change creates a new object).
  • Memory: Stored in String Constant Pool (SCP) if created using literals. Objects created with new go to the heap.

Example:

String str1 = "Hello";  // stored in SCP
String str2 = new String("Hello"); // stored in heap
Enter fullscreen mode Exit fullscreen mode

Here, modifying str1 or str2 will create a new object instead of changing the existing one.

2. StringBuffer in Java

  • Mutable: Values can be changed after creation.
  • Thread-safe: Methods are synchronized, which makes it safe to use in multi-threaded environments.
  • Speed: Slower than StringBuilder due to synchronization.
  • Memory: Stored in heap.

Example:

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");  // modifies the same object
System.out.println(sb);  // Output: Hello World
Enter fullscreen mode Exit fullscreen mode

3. StringBuilder in Java

  • Mutable: Values can be changed after creation.
  • Not thread-safe: Methods are not synchronized, so not safe in multi-threaded environments.
  • Speed: Faster than StringBuffer (no synchronization overhead).
  • Memory: Stored in heap.

Example:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);  // Output: Hello World
Enter fullscreen mode Exit fullscreen mode

Common Methods in StringBuffer & StringBuilder

Both classes share the same methods. Some useful ones are:

  1. append() – Adds text at the end
  2. insert() – Inserts text at a position
  3. replace() – Replaces part of the text
  4. delete() – Deletes part of the text
  5. reverse() – Reverses the text
  6. charAt(index) – Returns character at given index
  7. setCharAt(index, ch) – Sets character at given index
  8. length() – Returns current length
  9. capacity() – Returns current buffer capacity
  10. ensureCapacity(n) – Ensures minimum capacity (increases if needed)

Example:

package stringlearn;

public class StringBuilderMethods {
     public static void main(String[] args) {

            StringBuilder sb = new StringBuilder("Hello");                                      // Create a StringBuilder object

            // 1. append()
            sb.append(" World");
            System.out.println("append: " + sb); // Hello World

            // 2. insert()
            sb.insert(5, " Java");
            System.out.println("insert: " + sb); // Hello Java World

            // 3. replace()
            sb.replace(6, 10, "Python");
            System.out.println("replace: " + sb); // Hello Python World

            // 4. delete()
            sb.delete(5, 12);
            System.out.println("delete: " + sb); // Hello World

            // 5. reverse()
            sb.reverse();
            System.out.println("reverse: " + sb); // dlroW olleH
            sb.reverse(); // reverse back

            // 6. charAt() & setCharAt()
            System.out.println("charAt(1): " + sb.charAt(1)); // e
            sb.setCharAt(0, 'h');
            System.out.println("setCharAt: " + sb); // hello World

            // 7. length()
            System.out.println("length: " + sb.length()); // 11

            // 8. capacity() & ensureCapacity()
            System.out.println("capacity: " + sb.capacity()); // default 16 + length
            sb.ensureCapacity(50);
            System.out.println("capacity after ensure: " + sb.capacity()); // >= 50
        }
}


Enter fullscreen mode Exit fullscreen mode

When to Use What?

Use String

  • When you don’t expect modifications
  • For constants and small text values

Use StringBuffer

  • When working with multi-threaded applications that need thread safety

Use StringBuilder

  • When you need fast, efficient string modifications in a single-threaded environment

Top comments (0)