There are many differences between String
and (StringBuilder
or StringBuffer
) like mutability and many string operations
May be this question seems a bit silly, but I want to know for the sake of programming paradigm.
I want to ask, why has Java implemented another class, StringBuilder
or StringBuffer
for a data structure like String
. Why have they not given those features in String
itself.
Why not make String
itself thread-safe or provide some extra features that StringBuilder
or StringBuffer
has?
String is immutable and there are many reason and also benefit to it. Why? and what the necessity of it? (very popular topic ) search or read those why-is-string-immutable-in-java or why-string-is-immutable-in-java
Now Some one need to do frequent String operation here comes StringBuffer which is thread safe (synchronized).
Now some one can still use StringBuffer when thread safety is not necessary, but that would be slow. That's why both of them is important.
String's are differently handled by jvm
If those features of StringBuffer
was added it will not be immutable any more.
Update : point 2 and 3 are altered from the comment of @Jon Skeet.