Which among String or String Buffer should be preferred when there are a lot of updates required to be done in the data?

StringBuffer is preferred when there are a lot of updates to be made to a string, because String objects are immutable. This means that whenever you want to make a change to a string, a new string object must be created to represent the modified version of the original string. This can be inefficient if you are making a lot of changes, because it requires a lot of memory allocation and deallocation to create and discard all of these intermediate string objects.

On the other hand, StringBuffer is mutable, which means that you can modify the contents of a StringBuffer object directly without creating a new object. This can be more efficient when you need to make many changes to a string.

Here is an example of how you might use StringBuffer to efficiently build up a long string by repeatedly appending smaller strings:

StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append("a"); } String s = sb.toString();


Note that in Java 11 and later, the StringBuilder class can be used as an alternative to StringBuffer. StringBuilder has the same behavior as StringBuffer, but it is not thread-safe (meaning it does not have the same level of synchronization as StringBuffer). This makes it slightly faster, but it is not recommended for use in multi-threaded applications.

Comments

Popular posts from this blog

Can we make the main() thread a daemon thread?

What are the Memory Allocations available in JavaJava?

What is the default value stored in Local Variables?