Differences between StringBuilder and StringBuffer in Java
StringBuffer and StringBuilder classes were added in JDK to overcome the problem of not able to change the characters of a String object in Java. The String object is immutable and hence once created, can not be modified. But sometimes application requirements call for a lot of frequent changes in a String.
The StringBuffer and StringBuilder classes have been created to cater to these requirements. These classes have methods like append, replace and insert which actually modify the character array represented by the instance. However the StringBuffer and StringBuilder classes differ from each other in the following aspects:
- 1) The methods of StringBuffer class are marked as synchronized while that of StringBuilder are not.
- 2) StringBuffer was introduced earlier and hence is more popular however StringBuilder gives better performance in single threaded applications.
- 3) There are some methods which are explicitly defined in one of the class out of StringBuffer or StringBuilder but is not present in the other. Some examples include:
a) substring method is overridden in StringBuffer but StringBuilder class inherits this method from AbstractStringBuilder super class.
b) subSequence method is overridden in StringBuffer but StringBuilder class inherits this method from AbstractStringBuilder super class.
These differences in methods occur because of the fact that some methods from StringBuffer class are being used inside the JDK and support from them can not be withdrawn now.
- 4) As of JDK 1.7, the string object concatenation is being handled internally by using StringBuilder instance. The following line of code which tries to concatenate two string objects using the + operator:
System.out.println(new String("a") + new String("b"));
is converted into the following piece of code by the compiler:
System.out.println((new StringBuilder(String.valueOf(new String("a")))).append(new String("b")).toString())
Prior to JDK 1.5, this was done by using StringBuffer instance. It is worth mentioning here that the concatenation of String literals is optimized by the compiler which means a source code line:
System.out.println("a" + "b");
is converted into: