StringBuffer vs StringBuilder in JavaLast Updated : 10 Jan 2026 Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since JDK 1.5. ![]() What is StringBuffer in Java?StringBuffer is a mutable class that is used to create and modify strings without creating new objects. It is thread-safe that means, it is safe to use in multi-threaded environments. ExampleThe following example demonstrates the use of StringBuffer: Output: hellojava The append() method modifies the same StringBuffer object that proves it is mutable. What is StringBuilder in Java?StringBuilder is a mutable class in Java similar to StringBuffer, but it is not thread-safe. It is faster than StringBuffer and it is commonly used in single-threaded applications. ExampleThe following example demonstrates the use of StringBuilder: Output: hellojava Here, the same StringBuilder object is updated using append() that shows the efficient and fast string modification. Difference Between StringBuffer and StringBuilder ClassesA list of differences between StringBuffer and StringBuilder classes are given below:
Performance Test of StringBuffer and StringBuilderLet’s look at a program that compares the performance of the StringBuffer and StringBuilder classes. ExampleThe following example demonstrate how to test the performance of StringBuffer and StringBuilder. Output: Time taken by StringBuffer: 16ms Time taken by StringBuilder: 0ms In the above example, both StringBuffer and StringBuilder append a string multiple times, but StringBuilder executes faster because it is not synchronized, whereas StringBuffer is thread-safe and has extra overhead. Next TopicHow-to-create-immutable-class-in-java |
We request you to subscribe our newsletter for upcoming updates.