
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between StringBuffer and StringBuilder in Java
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 a 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.
What is StringBuilder?
The StringBuilder class in java is used to create and change a sequence of characters. In a regural string once the characters are created it cannot be changed but with the StringBuilder the characters can be modified. Between String, StringBuffer, and StringBuilder ? StringBuilder is the fastest when used in a single-threaded program.
Example of StringBuilder
The following is an example of StringBuilder in Java:
public class StringBuilderExample{ public static void main(String[] args){ StringBuilder builder=new StringBuilder("Hi"); builder.append("Java 8"); System.out.println("StringBuilderExample" +builder); } }
The output of the above Java program is:
StringBuilderExampleHiJava 8
What is StringBuffer?
The StringBuffer class in java is mutable sequence of characters. StringBuffer can be used to easily modify the content of a String. It provides many useful methods to manipulate a string.
Example of StringBuffer
The following is an example of StringBuffer in Java:
public class StringBufferExample{ public static void main(String[] args){ StringBuffer buffer=new StringBuffer("Hi"); buffer.append("Java 8"); System.out.println("StringBufferExample" +buffer); } }
The output of the above Java program is:
StringBufferExampleHiJava 8
Difference between StringBuilder and StringBuffer
The following table shows the difference between StringBuilder and StringBuffer:
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 |