String, StringBuilder and StringBuffer in Java

String, StringBuilder and StringBuffer in Java

Detailed Explanation of String, StringBuilder and StringBuffer in Java

In Java, String is immutable, meaning any modification creates a new object, making it thread-safe but slower and memory-intensive for frequent changes. StringBuilder is mutable, allowing direct modifications to the same object, making it faster but not thread-safe, suitable for single-threaded environments. StringBuffer is also mutable and thread-safe due to synchronization, but slightly slower than StringBuilder, ideal for multi-threaded scenarios requiring safe string operations. let’s understand one-by-one in details

String , StringBuilder and StringBuffer
  • String
  • String Builder
  • String Buffer

String

The String class in Java is immutable. This means that once a String object is created, it cannot be changed. If you modify a string (e.g., by concatenating or replacing characters), a new String object is created instead of modifying the original one.

This immutability ensures that Strings are thread-safe by design, meaning multiple threads can access the same String object without causing any issues. However, since every modification creates a new object, using String for repetitive operations (like appending or concatenation) can lead to higher memory usage and slower performance.

If we modify or update the value of String then java creates a new String object instead of modifying or updating the original String .

On update or modify of string it create new string every time that’s why string performance is slow in java

Example of String

String s = "Virat";  
s = s + " Kohli"; // Creates a new String object  
System.out.println(s); // Output: Virat Kohli

Explanation

In the example above, Strings in Java are immutable, meaning once a String is created, it cannot be changed. When we write s = s + ” Kohli”, the original String “Virat” remains unchanged. Instead, Java creates a new String object with the value “Virat Kohli” and assigns it back to the variable s.

So now, the original object with “Virat” still exists in memory (unless garbage collected), and the variable s refers to the newly created object “Virat Kohli”. This behavior ensures thread safety but can be inefficient for frequent string modifications, which is why StringBuilder or StringBuffer is preferred in such cases.

String Builder

The StringBuilder class in Java is also used to work with strings and is similar to StringBuffer in many ways. Like StringBuffer, it modifies the same object instead of creating a new one every time you make a change. This makes StringBuilder more memory-efficient compared to the String class.

However, StringBuilder is not thread-safe. This means it does not use synchronization, so if multiple threads try to access and modify a StringBuilder object at the same time, it can lead to problems like data inconsistency. But because it avoids synchronization, StringBuilder is faster than StringBuffer in situations where thread safety is not a concern.

StringBuilder is mutable in java that means if we update or modify the content of the object of StringBuilder then it does not create a new object it updates the existing or original object.

StringBuilder in java Supports faster operations for string manipulation because it modifies the same object when we update or modify content of the object

It is Faster than String because it avoids of creating multiple objects on manipulating the object

StringBuilder is not thread safe in java, that means it should not be used in multithreaded environments .

Example

StringBuilder sb = new StringBuilder("Virat");
sb.append(" Kohli"); // Modifies the same object
System.out.println(sb); // Output: Virat Kohli

Explanation

In this example, StringBuilder is mutable, meaning it allows changes to be made to the same object without creating a new one. When we call the append() method, it directly modifies the existing StringBuilder object by adding ” Kohli” to the original value “Virat”.

As a result, no new object is created, and the memory usage is more efficient compared to String. The final output is “Virat Kohli”, and it comes from the same StringBuilder object that was initially created. This is why StringBuilder is preferred for scenarios where frequent string modifications are needed.

String Buffer

The StringBuffer in Java is used to handle strings, but it works differently from the String class. When you modify a StringBuffer object, it updates the same object instead of creating a new one. This is why StringBuffer is more memory-efficient compared to the String class, which always creates a new object for every modification.

One important feature of StringBuffer is that it is thread-safe. This means multiple threads can safely access and modify a StringBuffer object without interfering with each other. It achieves this by using synchronization, which ensures that only one thread can use the methods of the StringBuffer at a time.

StringBuffer Similar to StringBuilder but it is StringBuffer has one more advantage: it is thread-safe. This means it can be safely used in multithreaded environments.

StringBuffer is Slightly slower than StringBuilder because of thread-synchronization overhead. That means it ensures that a resource (like a StringBuffer object) can be safely used by multiple threads at the same time without causing data corruption.

Example

StringBuffer sb = new StringBuffer("Virat");
sb.append(" Kohli"); // Modifies the same object
System.out.println(sb); // Output: Virat Kohli

Explanation

In this example, StringBuffer is mutable, meaning changes are made directly to the same object. When the append() method is called, it adds ” Kohli” to the existing “Virat” string within the same StringBuffer object.

What makes StringBuffer special is that it is thread-safe, meaning it ensures proper synchronization, so multiple threads can safely work with the same object. This is why it is suitable for multi-threaded environments. Unlike the String class, which creates a new object for every modification, StringBuffer updates the same object, making it more memory-efficient while still ensuring thread safety. However, this synchronization can cause a slight performance overhead compared to StringBuilder.

Difference Between String, StringBuilder and StringBuffer

Feature String StringBuilder StringBuffer
Mutability Immutable: Once created, it cannot be changed. Modifications create new objects. Mutable: Modifies the same object without creating a new one. Mutable: Modifies the same object without creating a new one.
Thread Safety Thread-safe by design (due to immutability). No special handling needed for multiple threads. Not thread-safe: Cannot be safely used with multiple threads. Thread-safe: Synchronization ensures safe access by multiple threads.
Performance Slower: Every modification creates a new object, leading to more memory usage. Faster: Avoids synchronization, making it quicker than StringBuffer. Slower than StringBuilder: Synchronization adds a slight performance overhead.
Use Case Use when strings are mostly constant or rarely modified, like in constants, keys, or simple operations. Use when frequent modifications to strings are needed in a single-threaded environment. Use when frequent modifications are needed in a multi-threaded environment.
Memory Usage High: New objects are created for every change, leading to more memory consumption. Low: Reuses the same object, saving memory. Low: Reuses the same object, but with synchronization overhead.

Example Comparison


public class StringExample {
    public static void main(String[] args) {
        // String (Immutable)
        String str = "Hello";
        str += " World"; // Creates a new object
        System.out.println("String: " + str);

        // StringBuilder (Mutable, Not Thread-Safe)
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World"); // Modifies the same object
        System.out.println("StringBuilder: " + sb);

        // StringBuffer (Mutable, Thread-Safe)
        StringBuffer sbf = new StringBuffer("Hello");
        sbf.append(" World"); // Modifies the same object with synchronization
        System.out.println("StringBuffer: " + sbf);
    }
}

Conclusion

  • Use String for simple, fixed strings
  • Use StringBuilder for fast, frequent changes in single-threaded applications.
  • Use StringBuffer for safe string operations in multi-threaded programs.

String Handling in Java Details Explanation

The String class in Java is immutable. This means that once a String object is created, it cannot be changed. If you modify a string (e.g., by concatenating or replacing characters), a new String object is created instead of modifying the original one.
This immutability ensures that Strings are thread-safe by design, meaning multiple threads can access the same String object without causing any issues. However, since every modification creates a new object, using String for repetitive operations (like appending or concatenation) can lead to higher memory usage and slower performance.

1. String
2. StringBuilder
3 StringBuffer

Difference Between String, StringBuilder and StringBuffer in Java

In Java, String is immutable, meaning any modification creates a new object, making it thread-safe but slower and memory-intensive for frequent changes. StringBuilder is mutable, allowing direct modifications to the same object, making it faster but not thread-safe, suitable for single-threaded environments. StringBuffer is also mutable and thread-safe due to synchronization, but slightly slower than StringBuilder, ideal for multi-threaded scenarios requiring safe string operations. let’s understand one-by-one in details

Leave a Comment