2

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?

8
  • 1
    stackoverflow.com/questions/355089/… Commented Jun 4, 2015 at 6:00
  • @bobs_007 - I know the difference between StringBuffer and StringBuilder, Please read my question i.e. bold in my post Commented Jun 4, 2015 at 6:02
  • If I could remember well String is Thread Safe! Commented Jun 4, 2015 at 6:02
  • 1
    String is immutable, StringBuilder is mutable. It's as simple as that. You can't add the StringBuilder features to String, because they're all about mutability. Commented Jun 4, 2015 at 6:05
  • 1
    @JonSkeet Its honor to even fix Jon Skeet's typos :) Commented Jun 4, 2015 at 6:07

1 Answer 1

7
  1. 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

  2. Now Some one need to do frequent String operation here comes StringBuffer which is thread safe (synchronized).

  3. Some one don't need thread safety here comes StringBuilder.

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What types of reasons are you trying to say about in your first point ?
Actually StringBuffer came before StringBuilder, and then Sun realized that it's incredibly rare to need its thread-safety, so they introduced StringBuilder. If StringBuilder had come first, I doubt that StringBuffer would ever have been introduced.
thanks Mr. @JonSkeet for making that clear.
reading those link will give you some idea and as I said its very popular topic so you can easily search .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.