Strings , I/O and formatting (Part-3 StringBuffer and StringBuilder)


I know you are an expert in Java string class now. But when handling an extremely dynamic environment which needs lots of modifications in a string and it's characters we need to use some additional techniques. StringBuffer and StringBuilder come to our help in these situations. As we discussed earlier strings are immutable objects.So when you change or modify string variables there is a tendency that you leave traces of used string objects in the memory which causes a memory overload or a memory leak.We can reduce this risk to a great extent using StringBuffer and StringBuilder in programming .

A general use of StringBuffer and StringBuilder class is to handle File I/O.There you have to deal with some ever-changing and large streams which need a unique method of memory handling and memory management. StringBuffer and StringBuilder can handle this large amounts of characters as blocks,pass one block and reuse the used memory portion again without allocating a new space in pool.Now you have some basic understanding about StringBuffer and StringBuilder. Let's discuss about the differences between these two.

The main difference between StringBuffer and StringBuilder is that StringBuffer is thread safe while Builder is not.(Thread safety basically means is that the object is immune to the concurrent modifications of it's attributes and methods.)You may start to love StringBuffer now because of it's wonderful ability..!!!.But sad to say that this ability can  reduce the performance of the program and as a result  Sun always encourage to use StringBuilder as much as possible unless you are not in a highly threaded environment. So enough of details now let's move to the practical part now.One thing to remember is that StringBuilder and StringBuffer is almost same except the difference discussed above.

StringBuffer a=new StringBuffer("Hasitha");
a.append(" is nice.");
System.out.println(a);
The output is "Hasitha is nice".You can clearly see how StringBuffer reduces the persistent of objects in the memory.So that's it for this post we'll talk about more in the next post.


Comments