String Builder and String Buffer

Why we need string buffer and string builder when we have string

Hi Readers,
If this question have struck your mind then i have answer for you. So there are some situations in Java programming when you need to manipulate already created string. Lets take an example

Example :-

String s = "This is line 1 of my email body";

I have taken this as string hoping that i only know about string. Later i want to add more lines to my email body. Now what you will do is

String s1 = s + "this is line no 2 of my email body";
Now you know because of immutability in string s1 will be created separately and then there will be two strings s and s1. And every-time you modify you email body, that many objects you will create. 
So it is really not a good idea to make so many objects.

Another case study

When you are working with url content and storing html from url. Your parser will parse the content line by line. So if you use String then there will be lot of objects and that is not a good idea as you will run out of memory very soon.

We have seen from two examples that when you need to modify string content very often then it is not a good idea to use string object. In Java programming language we have string buffer and string builder for this purpose. these classes also exist in java.lang package.

A very common use of string builder and string buffer comes when we work with file I/O with very large, ever changing streams of inputs. By using string buffer and string builder, you can handle block of data and then pass it on. And your builder / buffer is ready to work with next ser of data.

Use String Buffer

StringBuffer sb = new StringBuffer("this is line 1 of my email body");
sb.append("this is line 2 of my email body");

String buffer is synchronised so it is thread safe. And because of synchronisation it is a bit slow also.

Use String Builder

StringBuilder sb = new StringBuilder("this is line 1 of my email body");
sb.append("this is line 2 of my email body");

As we see using string builder is same as string buffer. String builder API has came with java version 5.

When to use string buffer and when to use string builder

String builder is preferred over string buffer in situations where Multithreading is not concern. String builder is not having synchronised methods, so it is faster than string buffer.

In some situations when Multithreading is your concern then you should use string buffer.
Otherwise string buffer and string builder works as same in JAVA.

Like and comment. You can also post your queries in comments.