Difference between String, StringBuffer and StringBuilder

 


In this tutorial we will see about difference between String, StringBuffer and StringBuilder. The most important difference that String Object is immutable but whereas StringBuffer/ StringBuilder are mutable. 

So what is immutable and mutable?
Once a value assigned to the String Object then the values can't be modified or changed is called as immutable class. On the other end the values can be changed and modified is called as mutable class.

How String works in Java?
Since String is immutable class we can't change the values once we placed in String Object. But we are able to modify the String value in Java and how its possible? Yes, whenever we modify a String Object new Object will be created. Below example will explain more details on how String works in Java.

String val = "My";
val = val + " Friend";
System.out.println(val);

Output of above code will be "My Friend". We assume that value of "val" gets concatenated. But internally Java creates Object for every String operation which we does. In Java we can create String Object by 2 ways like 

Using "new" operator:
String val = new String("My");

Using String Literal:
String val = "Friend";

Since String creates Objects at each time, we need to switch to StringBuffer or StringBuilder whenever we does String concatenations to avoid multiple String Objects creation and to increase our application performance.

Internally StringBuilder and StringBuffer or mutable, then what is the difference?
If we go back to JDK versions StringBuffer introduced in JDK 1.4 and StringBuilder introduced in JDK 1.5 version. 
Other main difference between StringBuffer and StringBuilder are synchronization. Internally StringBuffer is synchronized and StringBuilder is non-synchronized. Synchronized means it is thread safe and we can use when we implement any multi-threading operations, only one thread can modify StringBuffer at a time. Whereas StringBuilder is not thread safe.

Lets see how to create StringBuffer and StringBuilder

StringBuffer:
StringBuffer str = new StringBuffer();
str.append("My");
str.append(" Friend");
System.out.println(str);

StringBuilder:
StringBuilder str = new StringBuilder();
str.append("My");
str.append(" Friend");
System.out.println(str);






No comments:
Write comments