How does java clearly distinguish the application scenarios of String, StringBuilder and StringBuffer

Insert picture description here

1. Reasons for the introduction of StringBuilder
String class String is a final qualified type, String str="abc"+"bcs"; This code seems simple, but when the code runs, three string objects are actually created, namely : "Abs", "bcs", and "abcbcs", if the number of such splicing continues to increase, the program system will have a great performance consumption, so avoid using this method to modify the content of the string. Generally speaking, the operation of String is relatively simple, but due to the unmodifiable nature of String, in order to facilitate string modification, StringBuild and StringBuffer are provided.

2. The difference between StringBuilder and StringBuffer:

The biggest difference between String and StringBuffer is that the content of String cannot be modified, while the content of StringBuffer can be modified. Consider using StingBuffer if you frequently modify strings .
Let's take a look at the use of StringBuilder:

public class Test{
    
     
   public static void main(String[] args) {
    
     
      StringBuffer sb = new StringBuffer(); 
      sb.append("Hello").append("World"); 
      fun(sb); 
      System.out.println(sb); 
  } 
     public static void fun(StringBuffer temp) {
    
     
         temp.append("\n").append("www.bit.com.cn"); 
    } 
}

Each method of StringBuffer has a Synchronized keyword , so it is thread-safe, and StringBuilder is thread-unsafe.

Multi-threading can be understood as: each track is a thread, and multiple players competing on the track belong to a multi-threaded scene. The Synchronized keyword added by StringBuffer is equivalent to setting a boundary for the track, and there will be no chaos caused by competing players running to other players' tracks.

Three , summary: the difference between String, StringBuilder and StringBuffer: The
content 1.String can not be changed, StringBuilder and StringBuffer content can not be modified;
most of the functionality 2.StringBuilder and StringBuffer are similar;
3.StringBuffer synchronization mechanism, which belongs to a thread Safe operation, and StringBuilder does not use a synchronization mechanism, which is thread-unsafe.

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/109578163