Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at the differences between String, StringBuilder & StringBuffer in Java.
String:
Defined in java.lang package, String is a sequence of characters in Java. A string is considered as an object(reference type) and it is immutable i.e., once created, we cannot change the contents of it. Whenever we try to modify it, JVM will create a new object and returns its reference. The old value is left unchanged and available for the garbage collector.
StringBuffer & StringBuilder:
StringBuffer and StringBuilder are classes defined in java.lang package that allows modifying the underlying contents of it without creating a new object. StringBuilder is introduced in Java 1.5.
StringBuffer |
StringBuilder |
Synchronized | Not Synchronized |
Thread-safe | Not Thread-safe |
Slower | Faster |
As there is no need for thread safety and synchronization, StringBuilder is faster than StringBuffer.
Happy learning :).
Please leave a reply in case of any queries.