Home » Core Java » String vs StringBuffer vs StringBuilder

String vs StringBuffer vs StringBuilder

What is the difference between String,StringBuffer and StringBuilder ?

This is another important question in Java interviews.This question is getting popular now-a-days.We are going to see the point wise comparisons of String,StringBuffer and StringBuilder classes.

String ::

  1. String is a special class in java.lang package
  2. String class implements java.io.Serializable, Comparable<String> and CharSequence interfaces.
  3. String is immutable(unchangeable).
  4. String is thread safe.

StringBuffer ::

  1. StringBuffer belongs to java.lang package
  2. StringBuffer extends AbstractStringBuilder class and implements java.io.Serializable , CharSequence  interfaces.
  3. StringBuffer is mutable(changeable).
  4. StringBuffer is thead safe because its methods are synchronized.

StringBuider ::

  1. StringBuilder belongs java.lang package.
  2. StringBuilder extends AbstractStringBuilder class and implements java.io.Serializable , CharSequence  interfaces.
  3. StringBuilder is mutable(changeable).
  4. StringBuilder is not thread safe.

The above answers are sufficient to crack the interview question.But It is always better to know something extra.So, let us understand immutable and mutable part.String is immutable means once it is created, then it can not be changed.Let us see the below example to understand immutable and mutable meanings.Please go through the next two examples multiple times to understand it fully.This is a very tactical follow up question asked in interview round.

Now,Let us understand StringPool.
1.Basically StringPool is a pool of Strings inside Heap memory.
2. When we try to create a String without using new operator and using only double quote (Sting str= “abc”; ) then ,first the string is searched in string pool and then  if it is not present in String-pool then it is created.If the string is already present in  the string pool ,then only reference is returned.

3. Using new operator  (String str =new String(“Ajay”);) ,we always create String in heap memory and not in StringPool. However using intern() method we can put it into the StringPool or refer to any other object from the StringPool having exactly the same value.Let us see the below example to understand it.

 


Leave a comment

Your email address will not be published. Required fields are marked *

1 × 5 =