This is the 28th day of my participation in the August Text Challenge.More challenges in August

A String is not a String. What can you disassemble

Without further ado, we first through the source code to understand about

Analysis of the source code

We take the mainstream JDK1.8 source code to see, String internal storage structure is a char array.

There are several important constructors involved

// no argument constructor
public String(a) {
    this.value = "".value;
}


// String is the constructor of the argument
public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}


// char[] is the argument constructor
public String(char value[]) {
    this.value = Arrays.copyOf(value, value.length);
}


// StringBuffer is the constructor of the argument
public String(StringBuffer buffer) {
    synchronized(buffer) {
        this.value = Arrays.copyOf(buffer.getValue(), buffer.length()); }}// StringBuilder is the constructor of the argument
public String(StringBuilder builder) {
    this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
Copy the code

Above we have a brief look at the string source. The ones we tend to overlook are the constructors that take StringBuffer and StringBuilder as parameters, because these three data types are usually used separately, so this is a small detail we need to pay attention to

Now let’s look at the string method

  • Equals () compares whether two strings are equal

  • IndexOf () : The first subscript position of the query string

  • Contains () : Queries whether a string contains another string

  • ToLowerCase () : converts all strings toLowerCase

  • ToUpperCase () : converts all strings toUpperCase

  • Length () : indicates the length of the query string

  • Trim () : Trim the first and last Spaces of the string

  • Split () : Splits the string and returns an array of strings

. There are some others that I won’t go into here

Equals () compares whether two strings are equal

First look at the wave source

// This is the method we often use
public boolean equals(Object anObject) {
    // Return true for the same object reference
    if (this == anObject) {
        return true;
    }
    // Check whether the value to be compared is of type String. If not, return false
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            // Convert both strings to char arrays for comparison
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            // Loop over each character of the two strings
            while(n-- ! =0) {
                // If one of the characters is not equal, true false, otherwise continue to compare
                if(v1[i] ! = v2[i])return false;
                i++;
            }
            return true; }}return false;
}
Copy the code

String overrides the equals() method of Object. The equals() method needs to pass an Object parameter value. The equals() method will check whether it is String or false if it is not. Instanceof is used as follows:

Object oString = "123";
Object oInt = 123;
System.out.println(oString instanceof String); / / return true
System.out.println(oInt instanceof String); / / returns false
Copy the code

When the argument is a String, each character in the two strings is cyclically compared, returning true if all characters are equal and false otherwise.

OK other methods you can go in to see below yourself. Below we go to study through the interview question

Why should strings be final? (High-frequency interview questions)

Let me rephrase this question by asking what is the advantage of using final. From the source code of the String class, we can see that String is an uninheritable class modified by final.

So what are the benefits, if I may quote here from the father of Java

James Gosling, the father of the Java language, answered that he would have preferred final because it caches the result and doesn’t need to worry about who changes its value when you pass a parameter; If the class is mutable, you may need to copy a new value to pass the parameter, which will have a performance penalty.

James Gosling also said that another reason for forcing the String class to be immutable is security. When you call other methods, like some system-level operation, you might have a set of checks, and if you’re a mutable class, after you check it, its internal values might change again. This can cause serious system crash problems, which is an important reason for forcing the String class to be immutable.

Look is not a thief abstract ha ha. After all, is the father of Java, said not ordinary people can understand, I give you a look at the picture to understand:

Only if the string is immutable, we can implement string constant pool, string constant pool can cache strings for us, improve the efficiency of the program

Imagine if String were mutable. If S1 was changed, s2 would change as well. This would not match the expected result, so there would be no way to implement String constant pooling.

In summary, the first benefit of using final modifiers is security; The second benefit is efficiency

What is the difference between equals and equals? (High-frequency interview questions)

For basic data types, == is used to compare “values” for equality; For reference types, it is used to compare whether the reference address is the same.

The source code is as follows:

public boolean equals(Object obj) {
    return (this == obj);
}


public boolean equals(Object anObject) {
    // Return true for the same object reference
    if (this == anObject) {
        return true;
    }
    // Check whether the value to be compared is of type String. If not, return false
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            // Convert both strings to char arrays for comparison
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            // Loop over each character of the two strings
            while(n-- ! =0) {
                // If one of the characters is not equal, true false, otherwise continue to compare
                if(v1[i] ! = v2[i])return false;
                i++;
            }
            return true; }}return false;
}

Copy the code

String overrides equals() to compare two strings to see if they are equal.

What’s the difference between a String and a StringBuilder or a StringBuffer? (High-frequency interview questions)

Since strings are immutable, the performance of String concatenation is very low. Therefore, we need to use another data type, StringBuffer, which provides append and INSERT methods for concatenation of strings. It uses synchronized for thread safety, and I’ll show you two pictures. A little bit more intuitive

As you can see, StringBuffer uses synchronized to ensure thread-safety, so its performance is not very high. In JDK 1.5, StringBuilder also provides a method for concatenating appends and inserts. But it is not decorated with synchronized, and therefore performs better than StringBuffer. So this is another interview question to answer, why StringBuilder performs better than StringBuffer.

So when we use these. Consider the context in which it will be used. If you have high concurrency, you use StringBuffer, whereas if you have Builder, that’s the problem with everything, you get one thing, you have to sacrifice something else, like StringBuffer, which is safe, but low performance

OK, that’s all for today. I’ll see you next time

conclusion

The above is just a brief chat about string source code, I would like to say that any thing in JDK, no matter how small, contains a lot of things worth learning, to think about. We should be good at looking at the source code, learning their way.

overtones

Thank you for reading, if you feel that you have learned something, please like, follow. Also welcome to have a question we comment below exchange

Come on! See you next time!

To share with you a few I wrote in front of a few SAO operation

Talk about different strategy patterns (Bookmarks)

Copy object, this operation is a little SAO!