Java Wiki-String StringBuilder and StringBuffer

Abstract: This article will introduce the different among String, StringBuilder and StringBuffer. It will help to decide which one will be used during development.

String

The string is immutable and once a String is created, it cannot be modified. So when we change String, we always create a new reference to String.

Where store in memory

  1. create in “String constant pool”, which is inside the Heap memory and it can be reusable.
1
2
String str1 = "value";
String str4 = "value";//the "value" is reused
  1. create on the heap
1
String strHeap = new String("value")

Attention!

DONT DO Concatenation operation for String in the loop, because too many String will be stored.

StringBuffer

Use StringBuffer for concrete String in a loop.

VS String

  1. both are thread safe
  2. StringBuffer is implemented by using synchronized keyword on all methods.
  3. The string is immutable, StringBuffer is used to represent the values that can be modified.
  4. StringBuffer has high performance for the situation where String value need be modified too many times.

StringBuilder

VS StringBuffer

StringBuffer: thread safe
StringBuilder: not thread safe

why it is suggested by IDE or Sonar

Because if there isn’t the scenario that multiple threads operating on the same object, the StringBuilder has better performance, because the thread safe need synchronized keyword which reduces the performance.

This article discusses the thread safe or not.
https://blog.csdn.net/xiao__gui/article/details/8934832