String vs StringBuffer vs StringBuilder

String

  • For basic knowledge, you should read this.
  • Its immutable. It means once object is created then that object can not be modified.
  • Every immutable object is thread safe. Means same object can’t be shared by 2 or more threads at the same time.
  • Object created as a String and stored in Constant Literal Pool.

StringBuffer

  • Its mutable. It means once object is created then that object can be modified.
  • Object created as a StringBuffer and stored in Heap.
  • Each method (API) is synchronized means its thread safe. So we performance hit is also considerable.
Sample#1
Sample#2: Performance Test

StringBuilder

  • StringBuilder is same as StringBuffer but its methods are not synchronized.
  • It is more faster than StringBuffer.
  • If you are not using Threading logic, then better to use StringBuilder rather than StringBuffer.

Sample#1: Performance Test

 

 

3 Comments

  1. Pingback: Java Made Easy - Technical Jungle

Leave a Reply

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