String buffer and StringBuilder both are mutable classes which can be used to do operation on string objects such as reverse of string, concating string and etc. We can modify string without creating a new object of the string. A string buffer is thread-safe whereas string builder is not thread-safe. Therefore, it is faster than a string buffer. Also, a string concat + operator internally uses StringBuffer or StringBuilder class. Below are the differences.
Sr. No. | Key | String Buffer | String Builder |
---|---|---|---|
1 | Basic | StringBuffer was introduced with the initial release of Java | It was introduced in Java 5 |
2 | Synchronized | It is synchronized | It is not synchronized |
3 | Performance | It is thread-safe. So, multiple threads can’t access at the same time, therefore, it is slow. | It is not thread-safe hence faster than String Buffer |
4 | Mutable | It is mutable. We can modify string without creating an object | It is also mutable |
5 | Storage | Heap | Heap |
Example of StringBuilder
public class StringBuilderExample{ public static void main(String[] args){ StringBuilder builder=new StringBuilder("Hi"); builder.append("Java 8"); System.out.println("StringBuilderExample" +builder); } }
Example of StringBuffer
public class StringBufferExample{ public static void main(String[] args){ StringBuffer buffer=new StringBuffer("Hi"); buffer.append("Java 8"); System.out.println("StringBufferExample" +buffer); } }