In this chapter, we are going to learn at the String vs StringBuffer vs StringBuilder in Java.
In short, the basic difference between these three classes is of mutability and thread safety, where String is immutable and StringBuffer, StringBuilder both are mutable.
There are much more differences between these three class let’s discuss them in deep.
Also, avoid using String if its value will going to be changed in program, use StringBuffer instead.
1. What Is String?
The string is a very popular class in Java and we use lots of String to hold and manipulate data. Even a newbie programmer starts learning to programme with System.out.print.ln(“Hello world”);
The string is immutable and final in Java that means the value once assigned will never change. In fact, every time a new object will be created if you do some modification in a string object.
We can create a String object by two methods:
String value = “hello”; // recommended
String value = new String(“Hello”);
For more refer to Strings In Java.
2. What Is StringBuffer?
StringBuffer is mutable in Java, that means you can modify the value of a StringBuffer by using its own in-build methods.
Also, as like String, StringBuffer is also thread-safe and synchronized but it is less efficient than StringBuilder in terms of performance because it works in a synchronized manner.
Official Docs: Click here
3. What Is StringBuilder?
In Java, StringBuilder is an exact copy of StringBuffer, but with some changes, i.e StringBuilder is not Thread-safe and non-synchronized. Though, it is faster than StringBuffer.
I recommend, always use StringBuilder if thread-safety is not a factor else go with StringBuffer.
Example:
public class StringExample {
public static void main(String[] args) {
String s1 = "Hello";
s1 = s1 + "World"; // here two objects are created
System.out.println("String: " + s1);
StringBuilder s2 = new StringBuilder("Hello");
s2.append("world"); // single object is modified
System.out.println("StringBuilder: " + s2);
StringBuffer s3 = new StringBuffer("Hello");
s3.append("world"); // single object is modified
System.out.println("StringBuffer: " + s3);
}
}
4. String vs StringBuffer vs StringBuilder in Java
String | StringBuffer | StringBuilder |
Immutable | Mutable | Mutable |
Thread Safe | Thread Safe | Not Thread Safe |
It is a Final class | Syncronized | Not-syncronized |
Slower Than StringBuilder | Faster Than StringBuffer |
Recommended Read:
I hope you’ve understood String vs StringBuffer vs StringBuilder in Java.
Happy Learning!