String (String, StringBuffer, StringBuilder)

1. String

First of all, we have to make it clear that String is not a basic data type, but an object , and it is an immutable object. Looking at the source code, you will find that the String class is final (of course it cannot be inherited), and by looking at the JDK documentation, you will find that almost every operation that modifies a String object actually creates a brand new String object.

      A string is an object, so before initialization, its value is null. Here it is necessary to mention the difference between "", null, and new String(). Null means that the string has not been new, that is to say, the reference to the object has not been created, and no memory space has been allocated to it, while "" and new String() indicate that it has been new, but the interior is empty, but it has been created. A reference to an object needs to allocate memory space. For example: an empty glass, you can't say that there is nothing in it, because there is air in it, of course you can make it into a vacuum, the difference between null and " ", new String() is the same as vacuum and air.

      There is a very special place in strings, and that is the string pool. Whenever we create a string object, we first check whether there is a string with the same face value in the string pool. If there is, we will not create it again, and directly put back the reference to the object in the string pool. Create and put into the string pool and return a reference to the newly created object. This mechanism is very useful because it can improve efficiency and reduce memory space usage. Therefore, in the process of using strings, it is recommended to use direct assignment (ie String s=”aa”), unless it is necessary to create a new String object (ie String s = new String(”aa”)).

      The use of strings is nothing more than these aspects:

 

1. String comparison

 

         equals() ------ Determine whether the content is the same.

 

         compareTo() ------ Judge the size relationship of the string.

 

         compareToIgnoreCase(String int) ------ Ignore letter case when comparing.

 

         == ------ Determine whether the content is the same as the address.

 

         equalsIgnoreCase() ------ Judge whether the content is the same regardless of case.

 

         reagionMatches() ------ Compare whether parts of the string are the same (please refer to the API for details).

 

      2. String search

 

          charAt(int index) ------ Returns the character at the specified index index position, the index range starts from 0.

 

          indexOf(String str)------Retrieve str from the beginning of the string, and return the position of the first occurrence, and return -1 if it does not appear.

 

          indexOf(String str, int fromIndex);------ Retrieve str starting from the fromIndex-th character of the string.

 

          lastIndexOf(String str)------ Find the position of the last occurrence.

 

          lastIndexOf(String str, int fromIndex) ---- Find the position of the last occurrence from the fromIndex-th character of the string.

 

          starWith(String prefix, int toffset)-----Tests whether the substring of this string starting at the specified index starts with the specified prefix.

 

          starWith(String prefix)------Tests whether this string starts with the specified prefix.

 

          endsWith(String suffix)------Tests whether this string ends with the specified suffix.

 

      3. String interception

 

          public String subString(int beginIndex)------Returns a new string that is a substring of this string.

 

          public String subString(int beginIndex, int endIndex)------The returned string is the string from beginIndex to endIndex-1.

 

     4. String replacement

 

           public String replace(char oldChar,char newChar)。

 

           public String replace(CharSequence target, CharSequence replacement)------ Replace the original etarget subsequence with the replacement sequence, and return a new string.

 

           public String replaceAll(String regex, String replacement)------ Use regular expressions to match strings. Note that the first parameter of replaceAll is a regular expression.

 

二、StringBuffer

 StringBuffer and String are both used to store strings, but due to their different internal implementations, the scope they use is different. For StringBuffer, when he processes strings, if he modifies it, It does not create a new string object, so it is better than String in terms of memory usage.

      In fact, in terms of usage, many methods of StringBuffer are similar to those of the String class, and the functions represented are almost the same, except that when the StringBuffer is modified, it modifies itself, while the String class generates a new object, which is the biggest difference between them. difference.

      At the same time, StringBuffer cannot be initialized with =, it must generate a StringBuffer instance, which means you must initialize it through its constructor.

      In the use of StringBuffer, it focuses more on changes to strings, such as appending, modifying, and deleting, and the corresponding methods:

      1. append(): Append the specified content to the end of the current StringBuffer object, similar to the connection of strings, where the content of the StringBuffer object will change.

      2. insert: This method mainly inserts content in the StringBuffer object.

      3. delete: This method is mainly used to remove the contents of the StringBuffer object.

 

三、StringBuilder

StringBuilder is also a mutable string object. The difference between it and StringBuffer is that it is not thread-safe. Based on this, its speed is generally faster than StringBuffer. Like StringBuffer, StringBuider's main operations are append and insert methods. Both of these methods effectively convert the given data into a string and then add or insert the characters of that string into the string builder.

      The above is just a brief introduction to String, StringBuffer, and StringBuilder. In fact, for these three, we should focus more on the differences they only see. Only by understanding the differences between them can we use them better.

 

Fourth, the correct use of String, StringBuffer, StringBuilder

 

The scenarios used by these three are summarized as follows (reference: "Writing Quality Code: 151 Suggestions for Improving Java Programs"):

 

      1. String: The String class can be used in scenarios where strings do not change frequently, such as constant declarations, a small number of variable operations, etc.

 

      2. StringBuffer: If you frequently perform string operations (splicing, replacing, deleting, etc.) and running in a multi-threaded environment, you can consider using StringBuffer, such as XML parsing, HTTP parameter parsing, and encapsulation.

 

      3. StringBuilder: If you frequently perform string operations (splicing, replacing, deleting, etc.) and running in a multi-threaded environment, you can consider using StringBuffer, such as SQL statement assembly, JSON encapsulation, etc. (It seems that these two I also use |StringBuffer).

 

5. String concatenation method 

For strings, we often have to assemble them, and three methods of assembly have been improved in java: +, concat() and append() methods.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325027772&siteId=291194637