String, StringBuffer and StringBuilder difference

Differences

  1. Storage: String objects are stored in Heap area or SCP (string constant pool). When you create a string object using the "new" keyword the object is stored either in Heap area or SCP. When you use literal (=) to create a string object then that object is stored in SCP. StringBuffer and StringBuilder objects are stored in Heap area.
  2. Objects: String object is immutable whereas StringBuffer and StringBuilder object is mutable.
  3. Memory: If we change the value of a String regularly, then it will allocate more memory. StringBuffer consumes less memory, whereas StringBuilder occupies less memory.
  4. Thread safe: String methods are not thread safe. StringBuffer methods are synchronized, so they are thread safe. StringBuilder methods are non-synchronized so they are also not thread safe.
  5. Performance: String is the slowest among StringBuffer and StringBuilder. StringBuffer is slower than StringBuilder but faster than String. StringBuilder is the fastest among String and StringBuffer.
  6. Use: If data is not changing frequently then you can use a String. If data is changing frequently then you should use a StringBuffer or a StringBuilder.


Comments

Popular posts from this blog

HashMap, TreeMap and LinkedHashMap difference

Collections in Java

OOPS Concept in Java