String is immutable whereas StringBuffer and StringBuilder are mutable classes.
String is one of the most widely used classes in Java. StringBuffer and StringBuilder classes provide methods to manipulate strings.
Since String is immutable in Java,whenever we do String manipulation like concatenation, sub-string, etc.it generates a new String.So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation.
StringBuffer vs StringBuilder
StringBuffers all public methods are synchronized.
StringBuffer provides Thread safety but at a performance cost , it reduce performance.
In most of the scenarios, we don’t use String in a multithreaded environment.
So Java 1.5 introduced a new class StringBuilder,
which is similar to StringBuffer except for thread-safety and synchronization.
StringBuffer has some extra methods such as substring, length, capacity, trimToSize, etc.
However,these are not required since you have all these present in String too.
That’s why these methods were never implemented in the StringBuilder class.
StringBuffer was introduced in Java 1.0 whereas StringBuilder class was introduced in Java 1.5 after looking at shortcomings of StringBuffer.
StringBuffer and StringBuilder are mutable objects in Java and they provide append(), insert(), delete(), and substring() methods for String manipulation.
StringBuffer is thread-safe and synchronized whereas StringBuilder is not.That’s why StringBuilder is faster than StringBuffer.
For String manipulations in a non-multi threaded environment, we should use StringBuilder , and in multithreaded environment always use StringBuffer class.
StringBuilder performs better than StringBuffer even in the case of a single-threaded environment. This difference in performance can be caused by synchronization in StringBuffer methods.
If you are in a single-threaded environment or don’t care about thread safety, you should use StringBuilder. Otherwise, use StringBuffer for thread-safe operations.
check link String in java
check program on this link : click here to understand program
Happy Learning , Have a great day ahead