Coders Packet

Difference between String, StringBuffer and StringBuilder in Java

By zeel ajadiya

Hello friends! In this Java tutorial, we are going to discuss String, StringBuffer, and StringBuilder, and also the difference between them using Java.

In Java language, the String class is nothing but an object that represents the array of char or sequence of char. Whereas StringBuffer is a class that represents the mutable(Modifiable), this is the same as a normal string except Strings are mutable in this case. Whereas StringBuilder also is a class that represents the mutable string, this is the same as StringBuffer except that it is non-synchronized.

We can create a String by using this:

String String_Example = "Hello World!";

We can create a StringBuffer by using this:

StringBuffer StringBuffer_Example = new StringBuffer("Hello World!");

We can create a StringBuilder by using this:

StringBuilder StringBuilder_Example = new StringBuilder("Hello world!");

Now let's compare the String, StringBuffer, StringBuilder:

String class is immutable, Whereas StringBuffer and StringBuilder class are mutable(Modifiable). you might be thinking then what is the difference between StringBuffer and StringBuilder class well they both are mutable but StringBuffer is synchronized(It means that it is thread-safe, two thread cant call method at the same time) whereas StringBuilder is non-synchronized(two thread can call a method at the same time).
String is slower and takes more memory as compare to StringBuffer and StringBuilder. Whereas StringBuffer is fast and takes less memory as compare to String. And last StringBuilder is the fastest and also takes less memory.
StringBuffer is less efficient than the StringBuilder class. 

As if we take an example then for concatenation operator (+) internally uses StringBuffer or StringBuilder class.

Download Complete Code


No comments yet