Saturday, August 08, 2009

String versus StringBuffer



Generally, we use the String and StringBuffer classes for manipulating the character data. Both, String and StringBuffer are available in "java.lang" package.


String class is used to represent the character strings that cannot be changed. In other words, String type objects are read-only and immutable. StringBuffer objects represent the character strings that can be changed.

The other difference between the two is the performance. StringBuffer is much faster than that of String class when performing concatenations. Following lines of code is used to perform the concatenation.

String:
String string = new String("Java ");
string += "Language";

As String class is immutable, the initial string is first converted into StringBuffer and append the second string, then converts it back to String object using the toString() method.

StringBUffer: String buffer class has an "append()" method to concatenate the string data.
StringBuffer strBuf = new StringBuffer("Java ");
strBuf.append("Language");

First method - created three objects. initial String object, temporary StringBuffer and String object to hold the converted StringBuffer data.

Second method - everything is done with just one object creation, i.e. StringBuffer, and appends the data to the StringBuffer.

Overall, Using the StringBuffer there is no need of conversion from String->StringBuffer, and converting back to String, which is an expensive operation. So StringBuffer is a best option for developers to choose when they want to manipulate the character string data.

1 comment:

  1. From JDK5 onwards you can use Stringbuilder in place of StringBuffer in Java , StringBuilder is much faster than StringBuffer but not suitable for concurrent programming.

    Javin
    How to use synchronized block in Java

    ReplyDelete

È