Difference b/w String , StringBuffer &Stringbuilder

Posted on Updated on

1) MutabilityString is immutable (Once created, cannot be modified) while StringBuffer is mutable (can be modified).

Example –
String is immutable:

String str = "Hello World";
str = "Hi World!";
  • In first statement an object is created using string literal “Hello World”, in second statement when we assigned the new string literal “Hi World!” to str, the object itself didn’t change instead a new object got created in memory using string literal “Hi World!” and the reference to it is assigned to str.
  • So basically both the objects “Hello World” and “Hi World!” exists in memory having different references(locations).

Lets see StringBuffer mutability

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
  • In the first statement StringBuffer object got created using string literal “Hello” and in second statement the value of the object got changed to “Hello World” from “Hello”. Unlike Strings here the object got modified instead of creating the new object.
  • Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable.

String Builder 

The only difference is that StringBuilder and StringBuffer is that String buffer is thread safe.

  • If your string is not going to change use a String class because a String object is immutable.
  • If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder  is good enough.
  • If your string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer  is synchronous so you have thread-safety.

aydt9

Leave a comment