A little summary of java String class

1. Important features:
        
          String String constant ---" is an immutable quantity. The String class can be used in scenarios where the string does not change frequently, such as constant declarations and a small number of variable operations.
         
          StringBuffer String variable (thread safe) --- "Running in a multi-threaded environment, and frequent string operations (such as splicing, replacement, deletion, etc.), you can consider using StringBuffer,
                                                   such as XML parsing, HTTP parameter parsing and encapsulation.
         
          StringBuilder string variable (non-thread safe) --- "Running in a single-threaded environment, and frequent string operations (such as splicing, replacement, and deletion, etc.), you can consider using StringBuilder,
                                                     such as SQL statement assembly, JSON encapsulation, etc.
   1.2 Three ways to create strings:
            use the new keyword to create strings, such as String s1 = new String("abc");

            Specify directly. For example, String s2 = "abc";-----" uses direct specification or pure string concatenation to create a String object, then only the strings in the String pool will be checked and maintained. If
                                                   there is no pool, create one in the pool. That's it! But it will never create the String object again in the stack area.

            Use concatenation to generate a new string. For example String s3 = "ab" + "c";

      Principle 1: When using any method to create a string object s=X, the Java runtime (running JVM) will take this X to find out whether there is a string object with the same content in the String pool, if not, then Create a string s in the pool, otherwise, don't add it to the pool.
 
      Principle 2: In Java, as long as you use the new keyword to create an object, a new object will be created (in the heap or stack area).
 
      Principle 3: Use direct specification or use pure string concatenation to create a String object, only the strings in the String pool will be checked and maintained. If there is no one in the pool, create one in the pool. But it will never create the String object again in the stack area.
 
      Principle 4: To create a String object using an expression containing variables, not only will the String pool be checked and maintained, but a String object will also be created in the stack area.


2. String feature [cannot be inherited]:

           The String class is a final class, which means that the String class cannot be inherited, and its member methods are all final by default. The
         
           String class actually stores strings through [essential] char arrays [implements the charsequence interface]
 
           to String objects. Any changes made will not affect the original object, and any related change operations will generate new objects [such as concat sub replace]
   
    2.2 JVM constant pool:
           The data in the constant pool are those determined during compilation and saved in the compiled some data in the .class file. In addition to containing all 8 basic data types
          (char, byte, short, int, long, float, double, boolean), there are constant values ​​of String and its arrays, and some symbolic references in text form.

    2.3 java stack [data sharing]:
            The stack is characterized by faster access (than heap blocks), but small space, fixed data life cycle, and can only survive until the end of the method.

            [Example]: such as boolean b = true, char c = 'c', String str = "123"
                      true, c, 123, the right side of these equal signs refers to the content that can be determined during compilation, and are maintained in constants The first one on the left of the equal sign b, c, str in the pool
                      refers to a reference, and the content of the reference is the address of the data on the right side of the equal sign in the constant pool
                      boolean, char, String These are the types of references
             
       2.4 String [intern ()] and other basic data types are the same: first see if there is data to be created in the constant pool, return the address of the data if there is, create one if not.

       2.5String += "hello" or string concatenation +
                               [Multiple builder objects will be generated] Every time the compiler encounters "+", it will create a new StringBuilder, then call the append method, and call the toString method to generate new string.
                                         
                                ---"will be automatically optimized by JVM to: StringBuilder str = new StringBuilder(string);----"Multiple "+" will create many StringBuilder objects
                                                        str.append("hello");
                                                        str.toString( );

         2.6 String's concat()--"
                                By copying the string twice, a new character array buf[] is generated, and then according to the character array buf[], a new String object comes out and the
                                concat method is called N times, which will happen N*2 array copies and new N String objects are a waste of time and space.
        
    2.7 String rewrites equals()----"== compares the address of the reference type variable, and the value of the basic type variable
                                  equals() compares not the address but the value


3. StringBuffer feature [thread safety]:
            StringBuffer is the same as StringBuilder, it maintains a char array at the bottom layer, and puts characters into the char array every time it appends. In the final sb.toString(),
            use A new String() method converts the contents of the char array to String. The whole process is a new StringBuilder object and a String object

        3.1 Same as StringBuilder, appending in append() will create an object only once, and append it on the original basis

        3.2 are used in environments where string operations are frequently performed

        3.3 For indirect addition (that is, including string references), the form is s1+s2+s3; the efficiency is lower than that of direct addition (String str = "111" + "222" + "333"), because the compiler does not Reference variables are optimized.
            Compile-time optimization:
            [Example] String a = "hello2"; String b = "hello" + 2; ------" a==b is optimized to hello2 during compilation, so it points to the same constant pool during runtime Address
                  String a = "hello2"; String b = "hello"; String c = b + 2;----"! There is a reference to a==c, which cannot be optimized at compile time, the generated object is stored on the heap, and the address is inconsistent
                  String a = "hello2"; final String b = "hello"; String c = b + 2;---- -"a==c final definition, b is directly replaced by the real value at compile time, the address is the same as
                  String a = "hello2"; final String b = getHello(); String c = b + 2;-----"Assignment Returned by the method call, the value of b can only be known during operation, so the address is inconsistent
    
               String str1 = "I"; str1 += "love"+"java"; (1) str1 = str1+"love"+"java";
                

4. StringBuilder features [thread unsafe]:

      
       4.1 The only performance loss point of StringBuilder is that when the char array is not enough, it needs to be expanded, and the expansion needs to be copied, which reduces the efficiency to a certain extent.
          Optimization: If you can estimate the length of the strings to be concatenated, try to use the constructor to specify their length.


5. How many objects are created by String str = new String("abc")
 
       5.1 The code does create only one object during runtime, the "abc" object on the heap

       5.2 An "abc" object is created in the runtime constant pool, and indeed only one String object is created during code execution.

       5.3 involves 2 String objects

6.toString() Every java class inherits the toString() method from the Object class. For example: println() compiler will automatically add toString(), no need to manually add

7. The difference between null and ""

         13.1String s=""; [allocated a memory space and stored a string object]
                declares an object instance, this reference has pointed to a memory space that is an empty string, which is an actual thing, so you can do anything with it

         13.2 String a=null; [null is unallocated heap memory space, and the reference does not point to any memory space]
                An empty object is declared, and no operation can be performed on the empty object (NullPointException is reported), except for = and == 

         13.3 String b; [Declare a string object, but no memory is allocated]
                In the definition of member variables, String s; is equivalent to String s=null;-----" is initialized to null

                In the definition of local variables (method variables), String s; is not equivalent to String s=null;, in this case, s must be explicitly assigned [otherwise an exception will be reported].
               
                Variables defined in a method must be assigned initial values, and the main() method is no exception, and the compiler will automatically assign initial values ​​outside the method.

    Solve the problem of empty strings:
             For the determination of empty strings, it is recommended to use apache-commons-lang  http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html

             There are isBlank/isNotBlank [including " "] and isEmpty/isNotEmpty [do not include " " for non-empty processing] methods [same judgment for null ""]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326869125&siteId=291194637