Sitemap

String vs StringBuilder vs StringBuffer

6 min readApr 1, 2024

--

There are some common misconceptions about use cases of String, StringBuilder, and StringBuffer in mind of programmers. To addressing these misconceptions requires a clear understanding of the differences between String, StringBuilder, and StringBuffer, as well as knowledge of their respective strengths, weaknesses, and best practices for usage. It’s essential for programmers to consider factors such as thread safety, performance characteristics and usage scenarios when choosing the appropriate string manipulation approach.

In this blog we are going to understand all these points about String, StringBuilder, and StringBuffer with examples.

String :

In Java and Kotlin, the String class represents a sequence of characters. It’s one of the most commonly used classes in these programming languages.
Strings can be created in various way, While creating object it allocates the memory , Lets understand deeply about memory allocation of string based on its way of creation

Memory Allocation of String:
1. String literals:
Strings created using string literals (e.g., “Pune”) are usually stored in the

string pool. Subsequent strings with the same value will typically reference the same memory location in the string constant pool.

String s1 = “Pune”

2. Dynamically constructed strings: Strings created dynamically using constructors or concatenation are stored on the heap like any other object.

String s3= new String(“Delhi”)
What is String constant pool? Let’s understand it first. String Constant Pool (SCP) :

SCP is a special memory area where all String literals are stored. When a String literal is encountered, it looks for the same String literal in the SCP. If the String literal already exists in SCP, Java uses the existing String literal from SCP. Otherwise, it creates a new String literal in SCP. This ensures that only one copy of a particular String literal is stored in the memory.

SCP is created when the class is loaded by the JVM and is destroyed when the JVM shuts down. SCP is not accessible by the garbage collector even if that object is not in use.

When a String object is created using the “new” keyword or with constructor, two objects are created: one in the heap area and one in SCP.

Lets understand this with below example:

String s1 = “Pune” // This will get store in the string pool

String s2 = “Mumbai” // This will get store in the string pool either

String s3 = “Pune”. // This refer to the same memory location as s1

String s4= new String(“Delhi”) // Creates object on the heap & one more object in SCP

String s5= new String (“Delhi”) // This creates object on the heap and refers old in SCP

Press enter or click to view image in full size
Memory allocation of String in Heap Memory and String Constant Pool

In above example, String s1 and s2 are created using literals so it create objects with values “Pune” and “Mumbai” in string pool with reference to s1 and s2 respectively.

And when we create string s3 with literal with value “Pune”. It will search for that value in string pool if it present it will not create new object, it will refer to already available object so no new memory allocation here. So objects S1 and s3 points to same value “Pune”.

In other hand when we create String with constructor it will create new object in heap memory each time like we create s4. It creates one more object in string pool too it created “Delhi” reference to Jvm internally.

Immutability of String:

Strings in Java and Kotlin are immutable, meaning once created, their values cannot be changed. any operation that appears to modify a string actually creates a new string object. This behavior can lead to increased memory usage, especially in scenarios with frequent string manipulation. However, the JVM’s garbage collector efficiently handles memory management, reclaiming memory occupied by unused string objects.

Well, these are heavy operations and take a lot of memory, to avoid garbage in the heap, Java came up with StringBuffer

Get Bhavana Wagh’s stories in your inbox

Join Medium for free to get updates from this writer.

StringBuffer:

  • Java has provided StringBuffer class that should be used for String manipulation. StringBuffer is mutable objects in Java.
  • It allows you to modify the contents of the string It provide append(), insert(), delete(), and substring() methods for String manipulation.
  • StringBuffer is designed to be thread-safe. All of its public methods are synchronized, meaning they are safe for use in multi-threaded environments. However, this synchronization can lead to performance overhead, especially in single-threaded scenarios.
  • StringBuffer was the only choice for String manipulation until Java 1.4. But, it has one disadvantage that all of its public methods are synchronized.

StringBuffer provides Thread safety but at its performance cost. In most of the scenarios, we don’t use String in a multithreaded environment. So Java 1.5 introduced a new class StringBuilder, which is similar to StringBuffer except for thread-safety and synchronization.

StringBuilder:

  • Unlike strings, StringBuilder is mutable, meaning you can modify its contents without creating a new object each time.
  • This makes it more efficient for string manipulation, especially when dealing with large strings or performing frequent modifications.
  • StringBuilder is not thread-safe, meaning it’s not suitable for concurrent access from multiple threads. However, it offers better performance compared to StringBuffer due to its lack of synchronization.
  • StringBuilder is commonly used when you need to perform mutable string manipulation in a single-threaded context.

As we learn about memory allocation of string let’s learn deeply about Mutability and thread safety features of String, StringBuffer and StringBuilder with code demonstrations.

Mutability:

Let’s understand how mutability feature works in string and strigBuider, It will makes the point more clear with coding.

Press enter or click to view image in full size

In this example, str1 remains unchanged after calling toUpperCase().

Instead, a new string object is created with the modified content, demonstrating the immutability of String.

the content of the StringBuilder object StringBuilder is modified by appending “ Maharashtra” to it, demonstrating the mutability of StringBuffer.

These examples shown the fundamental difference between String and StringBuilder in Java: String is immutable, while StringBuilder is mutable.StringBuilder and StringBuffer both act same as both are mutable.

Thread Safety:

String and StringBuilder are not thread-safe, meaning it’s not designed to be used safely in concurrent (multi-threaded) environments. On the other hand, StringBuffer is thread-safe,

as it synchronizes access to its methods, making it safe to use in multi-threaded scenarios. Lets understand this difference with coding example.

StringBuilder being as not thread safe

Press enter or click to view image in full size
StringBuilder being as not thread safe

In above example, two threads (thread1 and thread2) are concurrently modifying a StringBuilder object by appending characters. Since StringBuilder is not thread-safe, concurrent modifications can lead to unpredictable things, such as lost updates or corruption of data. Here in output length is also not same each time we run the app.

StringBuffer is being thread safe

Press enter or click to view image in full size
StringBuffer is being thread safe

In this example, StringBuffer is used instead of StringBuilder. Since StringBuffer is thread-safe due to its synchronized methods, concurrent modifications by multiple threads are handled correctly without data corruption or inconsistency.

In summary, StringBuilder is not thread-safe, while StringBuffer is thread-safe due to synchronization. If you need mutability in a multi-threaded environment, StringBuffer should be used to ensure thread safety.

As we are very clear about memory allocation, mutability, thread safety and performance feature of String , StringBuffer and StringBuilder.

Let’s compare them for better understanding of their purpose and use cases.

Press enter or click to view image in full size
Difference between String, StringBuffer and StringBuilder

I hope this was helpful! I appreciate you taking the time to read this post. Feel free to share it with anyone who might find it useful. If you have any further questions or feedback, please do not hesitate to comment below. Thank you

--

--