English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
String buffer and StringBuilder are mutable classes that can be used to perform operations on string objects, such as reversing strings, compressing strings, etc. We can modify strings without creating new string objects. String buffer is thread-safe, while StringBuilder is not thread-safe. Therefore, it is faster than string buffer. In addition, string concat +Operators are internally used by StringBuffer or StringBuilder class. Here are the differences.
Index | Key | String Buffer | String Generator |
---|---|---|---|
1 | Basic | StringBuffer was introduced in the initial version of Java | It was introduced in Java 5introduced |
2 | Synchronous | It is synchronous | Asynchronous |
3 | Performance | It is thread-safe. Therefore, multiple threads cannot access it at the same time, so it is slow. | It is not thread-safe, so it is faster than the string buffer |
4 | Mutable | It is mutable. We can modify the string without creating an object | It is also mutable |
5 | storage | heap | heap |
public class StringBuilderExample{ public static void main(String[] args){ StringBuilder builder = new StringBuilder("Hi"); builder.append("Java" 8"); System.out.println("StringBuilderExample" +builder); } }
public class StringBufferExample{ public static void main(String[] args){ StringBuffer buffer = new StringBuffer("Hi"); buffer.append("Java" 8"); System.out.println("StringBufferExample" +buffer); } }