What is a StringBuffer class and how does it differs from String class?

StringBuffer is a peer class of String that provides almost all functionality of strings. String represents fixed-length, immutable character sequences. Comparatively StringBuffer represents mutable, growable and writeable character sequences. But StringBuffer does not create new instances as string so it’s more efficient when it comes to intensive concatenation operation.

In Core Java, the StringBuffer class and the String class are both used to represent sequences of characters, but there are some key differences between them.

  1. Mutability:
    • String: Strings in Java are immutable, meaning once a String object is created, its value cannot be changed. Any operation that appears to modify a string actually creates a new string.
    • StringBuffer: StringBuffer is mutable, which means you can modify the content of a StringBuffer object without creating a new object.
  2. Performance:
    • Due to immutability, operations like concatenation on String objects may create many temporary objects, which can be inefficient in terms of memory and performance.
    • StringBuffer is designed to be more efficient for operations that involve frequent modifications. It provides methods for appending, inserting, deleting, and modifying characters in-place.
  3. Synchronization:
    • String: String objects are immutable and, therefore, inherently thread-safe. Multiple threads can safely read from a String object without the need for synchronization.
    • StringBuffer: StringBuffer is synchronized, making it safe for use in a multi-threaded environment. However, this synchronization comes with a performance cost. If you don’t need thread safety, consider using StringBuilder instead, which is similar to StringBuffer but without synchronization.

Here’s a simple example:

java
String str = "Hello";
str = str + " World"; // This creates a new string
StringBuffer stringBuffer = new StringBuffer(“Hello”);
stringBuffer.append(” World”); // Modifies the existing StringBuffer object

In general, if you need a mutable sequence of characters and you are working in a multi-threaded environment, you might choose StringBuffer for its synchronization features. Otherwise, if you are working in a single-threaded environment or do not need thread safety, you might prefer the more lightweight and faster StringBuilder class.