Java advanced String, StringBuffer, StringBuilder

Posted by drimades on Sat, 18 Dec 2021 13:31:26 +0100

1, String class

1. General

String: a string represented by a pair of ""
1.String is declared as final and cannot be inherited
2.String implements the serializable interface: it means that the string supports serialization
The Camparable interface is implemented: it means that the String can compare the size
3. final char[] value is defined inside string to store string data
4. Assign a value to a string by literal (different from new). At this time, the string value is declared in the string constant pool
5. The string constant pool will not store strings with the same content

2. Immutability of string

2.1 description

1. When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment.
2. When connecting an existing string, it is also necessary to assign a value to the memory area again. The original value cannot be used for assignment.
3. When calling the replace() method of String to modify the specified character or String, it is also necessary to re specify the memory area assignment, and the original value cannot be used for assignment.

2.2 code examples

@Test
public void test1(){
    String s1 = "abc";//Definition of literal quantity
    String s2 = "abc";

    s1 = "hello";
    System.out.println(s1 == s2);//Compare the address values of s1 and s2
    System.out.println(s1);
    System.out.println(s2);
    System.out.println("*************");

    String s3 = "abc";
    s3 += "def";
    System.out.println(s3);

    String s4 = "abc";
    String s5 = s4.replace('a', 'm');
    System.out.println(s4);
    System.out.println(s5);
}

2.3 diagram

3. Different methods of string instantiation

3.1 mode description

Instantiation method of String:
   method 1: defined by literal quantity
   mode 2: through new + constructor

3.2 code examples

@Test
public void test2(){
    //Through literal definition: at this time, the data javaEE of s1 and s2 is declared in the string constant pool in the method area.
    //Literal definition: manual declaration, not constructor
    String s1 = "javaEE";
    String s2 = "javaEE";

    //Through the new + constructor: the address values saved in s3 and s4 at this time are the corresponding address values after the data opens up space in the heap space.
    String s3 = new String("javaEE");
    String s4 = new String("javaEE");

    System.out.println(s1 == s2);//true
    System.out.println(s1 == s3);//false
    System.out.println(s1 == s4);//false
    System.out.println(s3 == s4);//false

    System.out.println("*************");
    Person p1 = new Person("Simon", 29);
    Person p2 = new Person("Simon", 29);
    //The name attribute is defined literally
    System.out.println(p1.name.equals(p2.name));//Comparison content
    System.out.println(p1.name == p2.name);

    p1.name = "zzh";
    System.out.println(p2.name);//Simon
}

3.3 interview questions

String s = new String(“abc”); How many objects are created in memory?
   two: one is the new structure in the heap space, and the other is the data in the constant pool corresponding to char []: "abc"

3.4 diagram

4. Comparison of string splicing and assignment

4.1 description

1. The splicing results of constants and constants are in the constant pool. And constants with the same content will not exist in the constant pool.
2. As long as one of them is a variable, the result is in the heap.
3. If the result of splicing calls the intern() method, the return value is in the constant pool

4.2 code examples

@Test
public void test3(){
    String s1 = "javaEE";
    String s2 = "hadoop";

    String s3 = "javaEEhadoop";
    String s4 = "javaEE" + "hadoop";
    String s5 = s1 + "hadoop";
    String s6 = "javaEE" + s2;
    String s7 = s1 + s2;

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

    String s8 = s6.intern();//The s8 returned value uses the "Java EE Hadoop" that already exists in the constant value
    System.out.println(s3 == s8);//true

}

@Test
public void test4(){
    String s1 = "javaEEhadoop";
    String s2 = "javaEE";
    String s3 = s2 + "hadoop";
    System.out.println(s1 == s3);//false

    final String s4 = "javaEE";
    String s5 = s4 + "hadoop";
    System.out.println(s1 == s5);//true
}

5. Common methods

int length(): returns the length of the string: return value length
char charAt(int index): returns the character at an index. return value[index]
boolean isEmpty(): judge whether it is an empty string: return value length == 0
String toLowerCase(): converts all characters in a string to lowercase using the default locale
String toUpperCase(): converts all characters in a string to uppercase using the default locale
String trim(): returns a copy of a string, ignoring leading and trailing whitespace
boolean equals(Object obj): compare whether the contents of strings are the same
Boolean equalsignorecase (string otherstring): similar to the equals method, case is ignored
String concat(String str): concatenates the specified string to the end of this string. Equivalent to "+"
Int CompareTo (string otherstring): compares the size of two strings
String substring(int beginIndex): returns a new string, which is the last substring of the string intercepted from beginIndex.
String substring(int beginIndex, int endIndex): returns a new string, which is a substring intercepted from beginIndex to endindex (excluding).

boolean endsWith(String suffix): tests whether the string ends with the specified suffix
boolean startsWith(String prefix): tests whether this string starts with the specified prefix
Boolean startswith (string prefix, int tofffset): test whether the substring of this string starting from the specified index starts with the specified prefix

Boolean contains (charsequences): returns true if and only if this string contains the specified char value sequence
int indexOf(String str): returns the index of the first occurrence of the specified substring in this string
int indexOf(String str, int fromIndex): returns the index of the first occurrence of the specified substring in this string, starting from the specified index
int lastIndexOf(String str): returns the index of the rightmost occurrence of the specified substring in this string
int lastIndexOf(String str, int fromIndex): returns the index of the last occurrence of the specified substring in this string, and reverses the search from the specified index
Note: indexOf and lastIndexOf methods return - 1 if they are not found

Replace:
String replace(char oldChar, char newChar): returns a new string obtained by replacing all oldchars appearing in this string with newChar.
String replace(CharSequence target, CharSequence replacement): replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement): replace all substrings of this string that match the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement): replace this string with the given replacement to match the first substring of the given regular expression.
boolean matches(String regex): tells whether the string matches the given regular expression
String[] split(String regex): splits the string according to the matching of the given regular expression.
String[] split(String regex, int limit): split the string according to the matching given regular expression. The maximum number is no more than limit. If it exceeds the limit, all the rest will be placed in the last element.

6. Conversion between string and other structures

6.1 conversion with basic data types and packaging classes

Conversion between string, basic data type and wrapper class
String -- > basic data type, wrapper class: call the static method of wrapper class: parseXxx(str)
Basic data type, wrapper class -- > String: call valueOf(xxx) overloaded by String

    @Test
    public void test1(){
        String str1 = "123";
//        int num = (int) str1;
        int num = Integer.parseInt(str1);
        String str2 = String.valueOf(num);
        String str3 = num + "";
        System.out.println(str1==str3);//str1 is in the constant pool and str3 is in the heap
    }

6.2 conversion between and character array

String -- > char []: call toCharArray() of string
Char [] -- > String: call the constructor of String

@Test
public void test2(){
    String str1 = "abc123";  //Title: a21cb3

    char[] charArray = str1.toCharArray();
    for (int i = 0; i < charArray.length; i++) {
        System.out.println(charArray[i]);
    }

    char[] arr = new char[]{'h','e','l','l','o'};
    String str2 = new String(arr);
    System.out.println(str2);
}

6.3 conversion between and byte array

Conversion between String class and byte array:
Code: String -- > byte []: call getBytes() of string
Decoding: byte [] -- > String: call the constructor of String

Encoding: String -- > bytes (understandable - > incomprehensible binary data)
Decoding: inverse process of encoding, byte -- > string (incomprehensible binary data -- > understandable

Note: during decoding, the character set used for decoding must be consistent with the character set used for encoding, otherwise garbled code will appear.

@Test
public void test3() throws UnsupportedEncodingException {
    String str1 = "abc123 China";
    byte[] bytes = str1.getBytes();//Use the default character set for encoding.
    System.out.println(Arrays.toString(bytes));

    byte[] gbks = str1.getBytes("gbk");//Use gbk character set for encoding.
    System.out.println(Arrays.toString(gbks));

    System.out.println("******************");

    String str2 = new String(bytes);//Decode using the default character set.
    System.out.println(str2);

    String str3 = new String(gbks);
    System.out.println(str3);//Garbled code. Cause: the encoding set and decoding set are inconsistent!

    String str4 = new String(gbks, "gbk");
    System.out.println(str4);//No garbled code. Reason: the encoding set and decoding set are consistent!

}

6.4 conversion between string, StringBuffer and StringBuilder

String -- > StringBuffer, StringBuilder: call StringBuffer and StringBuilder constructors
StringBuffer, StringBuilder -- > String: ① call the String constructor; ② StringBuffer, toString() of StringBuilder

7. Description of storage location of string constant pool in JVM

JDK 1.6 (JDK 6.0, Java 6.0): the string constant pool is stored in the method area (persistent area)
jdk 1.7: string constant pool stored in heap space
jdk 1.8: the string constant pool is stored in the method area (meta space)

2, StringBuffer, StringBuilder

1. Comparison of string, StringBuffer and StringBuilder

What are the similarities and differences among String, StringBuffer and StringBuilder?
String: immutable character 0 sequence; The bottom layer uses char [] array storage
StringBuffer: variable character sequence, thread safe and inefficient; The bottom layer uses char [] array storage
StringBuilder: variable character sequence, jdk5 0 new, thread unsafe, high efficiency; The bottom layer uses char [] array storage

2. Memory parsing of StringBuffer and StringBuilder

Take StringBuffer as an example:

String str = new String();//char[] value = new char[0];
String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};

StringBuffer sb1 = new StringBuffer();//char[] value = new char[16]; The bottom layer creates an array with a length of 16.
System.out.println(sb1.length());//
sb1.append('a');//value[0] = 'a';
sb1.append('b');//value[1] = 'b';

StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];

//Question 1 System. out. println(sb2.length());// three
//Question 2 Capacity expansion: if the underlying array of data to be added cannot hold enough, the underlying array needs to be expanded.
By default, the capacity expansion is twice the original capacity + 2,At the same time, the elements in the original array are copied to the new array.
Guiding significance: it is recommended that you use: StringBuffer(int capacity) or StringBuilder(int capacity)

3. Compare the execution efficiency of String, StringBuffer and StringBuilder

  StringBuilder > StringBuffer > String

4. Common methods in StringBuffer and StringBuilder

Add: append(xxx)
Delete: delete(int start,int end)
Change: setcharat (int n, char CH) / replace (int start, int end, string STR)
Query: charAt(int n)
Insert: insert(int offset, xxx)
Length: length();
*Traversal: for() + charAt() / toString()

Topics: Java