Saturday, October 4, 2014

Stringbuffer and StringBuilder in java

The most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

String

One important characteristic of the Java String class is that the string object cannot be changed. Even though the String class contains methods such as replace andtoUpperCase, the object remains unchanged. Instead, these methods return a new String object. For example, the toLowerCase method returns a new String object with all of the characters in lower case. As a guideline, use Java String for string objects that will not change.

StringBuilder

The Java StringBuilder class represents string objects that can be changed. It contains methods such as append and insert that modify the string object. For example, the append method adds a string to the end of the StringBuilder object. The object is changed; no new object is created or returned. Generally use the StringBuilder class for string objects that will change.

StringBuffer

The Java StringBuffer class is just like StringBuilder. The primary difference is that StringBuffer issynchronized. In other words, multiple threads can safely process StringBuffer objects. However, additional overhead is required to make StringBuffer synchronized. So StringBuffer is slower than StringBuilder. You should use the StringBuffer class for string objects that will be changed by multiple threads of execution.

The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).


So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.

http://www.varemads.com/java-2/java-difference-stringbuffer-stringbuilder/

Here is Example of StringBuilder in JAVA

Hope this post is helpful for you...


No comments:

Post a Comment