1, the String

  • String class: represents a String. All string literals (such as “ABC”) in Java programs are implemented as instances of this class.

  • String is a final class that represents an immutable sequence of characters. Strings are constants and are represented by double quotes. Their values cannot be changed after creation.

  • The character content of a String object is stored in a character array value[].

public final class String
    implements java.io.Serializable.Comparable<String>, CharSequence {
        /** The value is used for character storage. */
        private final char value[];
        /** Cache the hash code for the string */
        private int hash; // Default to 0
Copy the code

String features:

public static void main(String[] args) {

        String s1 = "Hello";
        String s2 = "World";
        String s3 = "Hello" + "World";
        String s4 = s1 + "World";
        String s5 = s1 + s2;
        String s6 = (s1 + s2).intern();

        System.out.println(s3 == s4);
        System.out.println(s3 == s5);
        System.out.println(s4 == s5);
        System.out.println(s3 == s6);
	//false
        //false
        //false
        //true
}

/ / conclusion:
// queue constants join constants in the constant pool. And there will be no constant with the same content in the constant pool.
// queue the result is in the heap as long as either of them is a variable
// queue If the concatenated result calls intern(), the return value is in the constant pool
Copy the code

Specific conclusions

Virtual gateway String s1 = “a”;

Description: CREATES a string literal “A” in the string constant pool.

According to the principle, the cost of the project is equal to 0.

Note: In fact, the original “A” string object has been discarded and now produces a character in heap space

String S1 +”b” (“ab”). These changes to the string contents can result in a large number of copies if performed multiple times

String objects are kept in memory, reducing efficiency. If such an operation is put into a loop, it can have a big impact

Program performance.

Queue s2 = “ab”;

Description: Create a string literal of “ab” directly in the string constant pool.

Virtual Gateway String s3 = “A” + “b”;

S3 refers to the string “ab” that has been created in the string constant pool.

Queue s4 = s1.intern();

After calling intern(), the s1 object in the heapspace will place the “AB” string that already exists in the constant pool

Assign to S4.

1.2, String common methods

int length(a): Returns the length of the string: return value.length queuechar charAt(int index): Returns a character at an index return Value [index] queueboolean isEmpty(a): Check if it is an empty string: return value.length= =0String toLowerCase(a): Converts all characters in String to lowercase lent String using the default localetoUpperCase(a): Converts all characters in String to uppercase lent String using the default localetrim(a)Returns a copy of the string, ignoring leading and trailing whitespaceboolean equals(Object obj): Compares whether the contents of strings are the sameboolean equalsIgnoreCase(String anotherString): Similar to the equals method, ignore case anyway Stringconcat(String str): concatenates the specified string to the end of the string. Equivalent to "+" buying somethingint compareTo(String anotherString): Compares the size of two stringssubstring(int beginIndex): returns a new string, which is the last substring of the string, starting with beginIndex.  Stringsubstring(int beginIndex, int endIndex): returns a new string taken from beginIndexendIndex(Not included)A substring of.Copy the code
boolean endsWith(String suffix): tests whether the string ends the lent with the specified suffixboolean startsWith(String prefix): tests whether the string starts a queue with the specified prefixboolean startsWith(String prefix, int toffset): tests whether the substring of this string starting from the specified index starts queue with the specified prefixboolean contains(CharSequence s): If and only if this string contains the specifiedcharReturns a sequence of valuestrueint indexOf(String str): Returns the index lent at the first occurrence of the specified substring in the stringint indexOf(String str, int fromIndex): Returns the index at the first occurrence of the specified substring in the string, starting at the specified indexint lastIndexOf(String str)Returns the index lent at the right-most occurrence of the specified substring in the stringint lastIndexOf(String str, int fromIndex)IndexOf: returns the indexOf the last occurrence of the specified substring in the string, starting with the specified indexCopy the code
String replace(char oldChar, char newChar): returns a new string obtained by replacing all occurrences of oldChar in this string with newChar.  Stringreplace(CharSequence target, CharSequence replacement): Replaces all substrings of this string that match the target sequence of literals with the specified literal replacement sequence.  StringreplaceAll(String regex, String replacement): Replaces all substrings of this string that match the given regular expression with the given replacement.  StringreplaceFirst(String regex, String replacement): Replaces the first substring matching the given regular expression with the given replacement. boolean matches(String regex): Tells whether the string matches the given regular expression.  String []split(String regex): Splits the string based on the match of the given regular expression.  String []split(String regex, int limit): Splits the string according to the given regular expression, up to a maximum of limit, if more, all the rest into the last element.Copy the code

2, the StringBuffer

A StringBuffer was introduced in JDK1.0 as a thread-safe sequence of mutable characters that was immutable after String was created.

2.1 First look at the variables of StringBuffer

public final class StringBuffer extends AbstractStringBuilder
    implements java.io.Serializable.CharSequence {}abstract class AbstractStringBuilder implements Appendable.CharSequence {
   /** * The value is used for character storage. */
    char[] value; //value does not have a final declaration

   /** * The count is the number of characters used. */
    int count; //count Records the number of valid characters
}
Copy the code

The value here explains why a StringBuffer is mutable because it is not modified by final and can be expanded, as described below.

2.2. StringBuffer constructor

A StringBuffer, unlike a String, must be generated using a constructor. There are three constructors:

 StringBuffer() : The initial capacity is16 StringBuffer(int StringBuffer(String STR) :  StringBuffer of a specified capacity: initializes the content into a specified String contentCopy the code

2.3 StringBuffer expansion mechanism

If the initial capacity is not specified, the initial capacity is 16. If the initial capacity exceeds 16, the capacity will be expanded and a new array will be created.

Mechanism: Current capacity *2 + 2, see the code below

Capacity expansion:

public void ensureCapacity(int minimumCapacity) {
    if (minimumCapacity > 0)
        ensureCapacityInternal(minimumCapacity);
}

private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0) { value = Arrays.copyOf(value, newCapacity(minimumCapacity)); }}private int newCapacity(int minCapacity) {
        // overflow-conscious code
        // New capacity = the current length is moved 1 bit to the right by the bitwise operator and +2
        int newCapacity = (value.length << 1) + 2;
        // If the new capacity is smaller than the current capacity
        if (newCapacity - minCapacity < 0) {
            // New capacity = current capacity
            newCapacity = minCapacity;
        }
        Throw an exception if the new capacity is less than 0 or greater than the maximum otherwise return the new capacity
        return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)? hugeCapacity(minCapacity) : newCapacity; }Copy the code

If the specified capacity >0, call ensureCapacityInternal. If the specified capacity is large and the existing capacity is specified, then call newCapacity().


3, the StringBuilder

StringBuilder was introduced in JDK5 to address the StringBuffer’s thread-safety problems.