Java Foundation 16-String class (Buffer and Builder)

1. What is the essence of the String class?

 

 The output of the above code is the same, we enter the source code of the String class

In fact, the essence of a string is an array of characters, and a  String is actually a package of a char array.

Second, the classification of strings

1. Unchangeable string String: After the current object is created, the content of the object cannot be changed. Once the content changes, it is a new class
. 2. Variable string: StringBuffer/StringBuilder, after the current content is created, The content of the object can change, and the object does not change when the content changes

 

We output the above two pieces of code, although the reference name is the same, but when we reassign it, its hashcode has changed, that is, the address of str in memory has changed, although str="Sauron" is the same as str= "Luffy" has the same name, but it is actually two variables, that is, a space has been opened up in memory (constant pool) .

Third, the creation of String objects

1. Assign a literal directly:
String str1="abcd";
2. Through the constructor
String str2=new String("abcd");

 What is the difference between the two? Don't worry, see below

To talk about this problem, it is necessary to understand an area in memory, the constant pool .

Constant pool: The place where constants are stored, all refers to the method area
* Compiled constant pool: When the bytecode is loaded into the jvm, it stores the relevant information of the bytecode (not studied)
* Running constant pool: Stores constant data (Research)

Through this question, we will reveal 

Difference between String str4="abcd" and String str5=new String("abcd")?

 

How many String objects are created by the above code?

At most one str4 is created, at least not. If abcd already exists in the constant pool, direct reference does not create
str5. Create at most two String objects, at least one, and the new keyword will definitely create a memory area in the heap space, so create at least one

Let's look back at the second problem of different hashcodes. In fact, different values ​​​​have different addresses in the space opened up in the constant pool, when the value changes. That is, the address pointed to by this reference has changed.

The hashcodes of str and str10 are the same! Now we understand that as long as the value is the same, no matter what the name is, it points to the same address.

 

 

 

Fourth, the null value of the String object
1. Indicates that the reference is empty (null): no initialization, no memory space allocated
String str3=null;
2. The content is empty, it has been initialized, and memory space is allocated, but there is no content
5. Judging characters The string is not empty 1. The reference
cannot be null 2.
The character content cannot be an empty
string : The same as == in the object class, it is recommended that subclasses override the equals method to compare the content 7. Comparison of strings


1. Strings created with "" alone are direct quantities, and the compiler has determined that they are stored in the constant pool
. 2. Objects created with new String("") will be stored in heap memory and only created at runtime
. 3. Use String concatenators that only contain literals, such as "aa"+"bb", are also literals, which the compiler can determine and have been stored in the constant pool
4. Use characters that contain String literals (without final modifier) Objects created by string expressions (such as "aa"+s1) are created at runtime and stored in the heap

 

 

Eight, common methods of contact

 

    // One, String exercise, get the suffix name of the file name starting with hello 
    String filename="abc.java;hello.java" ;
     // 1. A good copy to split the string, get each name and extension 
    String [] name=filename.split(";" );
     for (String names : name) {
        System.out.println(names);
        // 2. Determine whether each name starts with hello 
        if (names.startsWith("hello" )) {
             // 3. Get the suffix of the file name, the last half of the last dot 
            names.lastIndexOf("." );
             // Intercept string 
            System.out.println(names.substring(names.lastIndexOf("." )));
        }
    }
    // 2. The first letter of the word is capitalized 
    String str7="willabcad" ;
     // 1. Get the first character and convert it to uppercase 
    String first=str.substring(0, 1 ).toUpperCase();
     // 2. Intercept the character String from 1 to the end 
    String last=str.substring(1 );
    System.out.println(first + last);
     // trim method eliminates leading and trailing spaces 
    System.out.println(" ab cd " .trim().length());
    System.out.println(" ab cd ".length());

Nine, StringBuilder and StringBuffer

Let's look at a small example

    // Use String/StringBuilder and StringBuffer to splice 30,000 times 
    long begin= System.currentTimeMillis();
    String str8="";
        for(int i=0;i<30000;i++) {
            str8+=i;
        }
        long end=System.currentTimeMillis();
        System.out.println(end - begin);
         // The performance of string splicing is very low, because a new object 
        StringBuffer is required every time sb= new StringBuffer("" );
         long begin2= System.currentTimeMillis() ;
             for ( int i=0;i<30000;i++ ) {
                sb.append(i);
            }
            long end2=System.currentTimeMillis();
        System.out.println(end2-begin2);
        StringBuilder sbr=new StringBuilder("");
        long begin3=System.currentTimeMillis();
        for(int i=0;i<30000;i++) {
            sbr.append(i);
        }
        long end3=System.currentTimeMillis();
    System.out.println(end3-begin3);
        }

After testing, sbr takes the shortest time, followed by sb, so use stringbuffer or stringbuilder to concatenate strings

StringBuilder and StringBuffer both represent variable strings, and the
only difference is the same function method;
stringbuffer: using the synchronized modifier, indicating synchronization, and ensuring thread safety when multiple processes are concurrent
stringbuilder: no synchronized, unsafe
common operation
chain programming
append, deleteCharAt

Guess you like

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