What is the difference between StringBuffer and String?

What is the difference between StringBuffer and String?

Even though String and StringBuffer sound similar, they are not the same. Both are a sequence of characters that are primarily used to create and manipulate strings. However, there are certain differences between. The following are the primary differences between String and StringBuffer.

Sting

StringBuffer

String class is immutable, i.e. once created cannot be changed

StringBuffer class is mutable, i.e. once created can be changed

String is stored in theĀ  Constant String Pool

Stringbuffer Is Stored In The Heap

String is thread safe

StringBuffer is thread safe

String cannot be used by two threads simultaneously.

String cannot be used by two threads simultaneously.

Once assigned String cannot be changed.

StringBuffer value can be changed, i.e. it can be assigned to a new value

String is slow and consumes more memory when one concat too many strings because it creates a new instance every time.

StringBuffer is fast and consumes less memory when one cancat strings.

String class overrides the equals() method of Object class.

StringBuffer class doesn't override the equals() method of Object class.

Cannot be converted.

String Buffer can be converted to the string by using toString() method.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.