[Java advanced] common classes in Java - String

Posted by engkeb0i on Thu, 24 Feb 2022 15:15:33 +0100

catalogue

01 string related

1.1 overview of string class

1.2 creation of string object

 1.2.2  String str1 = “abc”; And String str2 = new String("ABC"); What's the difference?

1.2.3 memory parsing of string with different splicing methods

1.2.4 an interview question

1.3 common methods in string

1.3.1 common method 1 in String

1.3.2 common method 2 in String

1.3.3 three common methods in String

1.4 conversion between string and other data types

1.4.1 conversion between string and basic data type

1.4.2 conversion between string and char []

1.4.3 conversion between String and byte []

1.5 StringBuffer and StringBuilder

1.5.1 difference between string, StringBuffer and StringBuilder

1.5.2 source code analysis of both

1.5.3 common methods in StringBuffer

1.5.4 efficiency comparison of string, StringBuffer and StringBuilder

01 string related

1.1 overview of string class

Understand the immutability of String

* String: 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 Comparable interface is implemented: it means that strings can compare sizes
     * 3. final char[] value is defined inside string to store string data
     * 4.String: represents an immutable character sequence. Abbreviation: non variability.
* embodiment: 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, you also need to assign a value to the memory area again. The original value cannot be used for assignment.
     *   3. When you call the replace() method of String to modify the specified character or String, you also need to reassign the memory area assignment, and the original value cannot be used for assignment.

     * 5. Assign a value to a string by literal means (different from new). At this time, the string value is declared in the string constant pool.
     * 6. Strings with the same content will not be stored in the string constant pool.

import org.junit.Test;

/**
 * String Use of
 */
public class StringTest {

   
    @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, true

        System.out.println(s1);//hello
        System.out.println(s2);//abc

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

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

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

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

1.2 creation of string object

String str = "hello";

//Essentially this value = new char[0];
String  s1 = new String(); 

//this.value = original.value;
String  s2 = new String(String original); 

//this.value = Arrays.copyOf(value, value.length);
String  s3 = new String(char[] a);

String  s4 = new String(char[] a,int startIndex,int count);

 1.2.2  String str1 = “abc”; And String str2 = new String("ABC"); What's the difference?

  • String constants are stored in the string constant pool for sharing
  • String non constant objects are stored in the heap

Practice

import org.junit.Test;

/**
 * String Use of
 */
public class StringTest {

    /**
     * String Instantiation method of
     * Method 1: through literal definition
     * Mode 2: through new + constructor
     *
     *
     */
    @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.
        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("Tom",12);
        Person p2 = new Person("Tom",12);

        System.out.println(p1.name.equals(p2.name));//true because it is defined literally in the class
        System.out.println(p1.name == p2.name);//true

        p1.name = "Jerry";
        System.out.println(p2.name);//Tom
    }
}

*Interview question: 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"

public class Person {

    String name; //Literal definition
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {

    }
}

public class StringAddTest {
  
    public static void main(String[] args){
        String s1 = "JavaEE";
        String s2 = "hadoop";


        String s3 = "JavaEEhadoop";
        String s4 = "JavaEE" + "hadoop";
        // s3 and s4 are literal quantities
        String s5 = s1 + "hadoop";
        String s6 = "JavaEE" + s2;
        String s7 = s1 + s2;
        // Splices with variable names are assigned values in heap space
        // ==Compare address values
        System.out.println(s3 == s4);//true
        System.out.println(s3 == s5);// false
        System.out.println(s3 == s6);//false
        System.out.println(s5 == s6);//false
        System.out.println(s3 == s7);//false
        System.out.println(s5 == s7);//false

        String s8 = s7.intern(); //The return value is in the constant pool
        System.out.println(s3 == s8);

    }
}

1.2.3 memory parsing of string with different splicing methods

The final returned result of String+ i of the design variable is in the heap space, and the "0" in the constant pool remains unchanged

After the final definition, s4 is equivalent to a constant, which is spliced in the constant pool, s1 = s5

1.2.4 an interview question

/**
 * An interview question
 */
public class StringTest {
    String str = new String("good");
    char[] ch = { 't', 'e', 's', 't' };

    public void change(String str, char ch[]) {
        str = "test ok";
        ch[0] = 'b';
    }
    public static void main(String[] args) {
        StringTest ex = new StringTest();
        ex.change(ex.str, ex.ch);
        System.out.println(ex.str);//good here is about value passing. It changes the value of the formal parameter, which has nothing to do with the argument in main
        System.out.println(ex.ch);//best
    }
}

1.3 common methods in string

1.3.1 common method 1 in String

public class StringMethodeTest {
    public static void main(String[] args){
        //int length() returns the length of the string: return value length
        String s1 = "HelloWorld";
        System.out.println(s1.length());
        //char charAt(int index) returns the character at an index. return value[index]
        System.out.println(s1.charAt(0)); //H
        System.out.println(s1.charAt(8));//l
        //boolean isEmpty() determines whether it is an empty string: return value length 0
        System.out.println(s1.isEmpty());//false
        //String toLowerCase() converts all characters in a string to lowercase using the default locale
        String s2 = s1.toLowerCase();
        System.out.println(s2);//helloworld
        System.out.println(s1);//HelloWorld, it hasn't changed
        //String trim() returns a copy of a string, ignoring leading and trailing whitespace
        String s3 = "  He llo Wo r ld  ";
        String s4 = s3.trim();
        System.out.println(s3);//  He llo Wo r ld
        System.out.println(s4);//He llo Wo r ld for login account


        //boolean equals(Object obj) compares whether the contents of the string are the same
        System.out.println(s2.equals(s1)); //false
        //Boolean equalsignorecase (string otherstring) is similar to the equals method, ignoring case
        System.out.println(s2.equalsIgnoreCase(s1));//true
        // String concat(String str) concatenates the specified string to the end of this string
        String s5 = "abc";
        String s6 = s5.concat("def");
        System.out.println(s6);//abcdef
        //Int CompareTo (string otherstring) compares the size of two strings

        String s7 = "abc";
        String s8 = "abd";
        System.out.println(s7.compareTo(s8));//-1. The return value is asker code difference, involving string sorting

        //String substring(int beginIndex) returns a new string, which is intercepted from beginIndex to endindex (a substring not included)
        String s9 = "Munich University of Technology";
        String s10 = s9.substring(2);
        System.out.println(s10); //Black University of Technology

        String s11 = s9.substring(0,3);
        System.out.println(s11); //Munich left closed right open
    }

1.3.2 common method 2 in String

public class StringMethodTest2 {
    public static void main(String[] args) {
        //boolean endsWith(String suffix) tests whether the string ends with the specified suffix
        String s1 = "HELLO WORLD";
        boolean b1 = s1.endsWith("RLD");
        System.out.println(b1);//true
        // boolean startsWith(String prefix) tests whether the string starts with the specified prefix
        boolean b2 = s1.startsWith("he");
        System.out.println(b2);//false
        //     boolean startsWith(String prefix) tests whether the string starts with the specified prefix
        boolean b3 = s1.startsWith("LL",2);
        System.out.println(b3);//true
        //Boolean contains (charsequences) returns true if and only if this string contains the specified sequence of char values
        String str = "WO";
        System.out.println(s1.contains(str));//true
        // int indexOf(String str) returns the index of the first occurrence of the specified substring in this string
        System.out.println(s1.indexOf("lol")); //-1
        //int indexOf(String str, int fromIndex) returns the specified substring. It is the first time in this string
        //    The current index starts from the specified index
        System.out.println(s1.indexOf("LO",2)); //3
        // int lastIndexOf(String str) returns the value of the rightmost occurrence of the specified substring in this string
        System.out.println(s1.lastIndexOf("LO")); //3
        //int lastIndexOf(String str, int fromIndex) returns the last of the specified substring in the string
        //The index at one occurrence, and the reverse search starts from the specified index
        System.out.println(s1.lastIndexOf("LO",2)); //-1
        
    }
}
// When do indexOf and lastIndexOf return the same value?
// There is only one result, or no result

1.3.3 three common methods in String

public class StringMethodTest3 {
    
    public static void main(String[] args){
        //String replace(char oldChar, char newChar)
        // Returns a new string, which is obtained by replacing all oldchars appearing in this string with newChar.
        String s1 = "TESTTEST";
        String s2 = s1.replace("T","B");
        System.out.println(s2); // BESBBESB change all characters
        String s3 = s1.replace("TE","B");
        System.out.println(s3); // Bstbstbst changes all characters

        // String replaceAll(String regex, String replacement)
        // Replace all substrings of this string that match the given regular expression with the given replacement.
        String str = "12hello34world5java678mysql910";
        System.out.println(str.replaceAll("\\d+", ","));
        //, hello,world,java,mysql, replace numbers with commas
        // boolean matches(String regex) tells whether the string matches a given regular expression.
        str = "12345";
        boolean matches = str.matches("\\d+"); //true
        System.out.println(matches);
        String tel = "0571-4323445";
        matches = tel.matches("0571-\\d{7,8}");//true, regular expression
        System.out.println(matches);

        str = "hello|world|java";
        String[] strs = str.split("\\|");// Divide into different numbers with | and pass in the array
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
        System.out.println("************");
        str = "hello.world.java";
        String[] strs2 = str.split("\\.");//With distinguish
        for (int i = 0; i < strs2.length; i++) {
            System.out.println(strs2[i]);
        }

    }


1.4 conversion between string and other data types

1.4.1 conversion between string and basic data type

import org.junit.Test;

/**
 * It involves the conversion between String class and other structures
 */
public class StringTest1 {

    /**
     * review
     *    String Conversion with basic data types and wrapper classes
     *
     *    String --> Basic data type and 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"; //In the constant pool
//       Convert String to basic data type
//        int num = (int)str1;// FALSE
        int num = Integer.parseInt(str1);
        // Convert basic data type to String

        String str2 = String.valueOf(num);   //"123"
        String str3 = num + "";//In heap space

        System.out.println(str1 == str3);   //false
    }

}

1.4.2 conversion between string and char []

public class StringTransferTest {
    public static void main(String[] args){
        String str1 = "123abc"; //Convert to 1bc32c output, first convert to char array, then reverse, and then convert to String
       char[] chars =  str1.toCharArray();
       for(int i = 0; i < chars.length; i++){
           System.out.println(chars[i]);
       }

       char[] charsArray = new char[]{'1','2','3','b','c','d'};
       String str2 = new String(charsArray);
        System.out.println(str2);
    }

}

1.4.3 conversion between String and byte []

import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * It involves the conversion between String class and other structures
 */
public class StringTest1 {

    /**
     * String Conversion between and byte []
     *
     * Code: String -- > byte []: call getBytes() of string
     * Decoding: byte [] -- > String: call the constructor of String
     *
     * Encoding: String -- > bytes (binary data that can be understood -- > but cannot be understood)
     * Decoding: the reverse process of encoding, byte -- > string (can't understand binary data -- > understand)
     *
     * Note: when decoding, it is required that 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";
        byte[] bytes = str1.getBytes();//Use the default character encoding set for conversion
        System.out.println(bytes.toString()); // Address value
        System.out.println(Arrays.toString(bytes));//[97, 98, 99, 49, 50, 51]

        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);// "abc123"

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

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

1.5 StringBuffer and StringBuilder

1.5.1 difference between string, StringBuffer and StringBuilder

/**
 * String,StringBuffer,StringBuilder The similarities and differences between the three?
 *
 * String:Immutable character sequence; The bottom layer uses char [] storage
 * StringBuffer:Variable character sequence; Thread safety and low efficiency; The bottom layer uses char [] storage
 * StringBuilder:Variable character sequence; jdk5.0 new, thread unsafe, high efficiency; The bottom layer uses char [] storage
 *
 */

1.5.2 source code analysis of both

/*
String StringBuffer StringBuilder difference?
String: The immutable character sequence is stored in char [] at the bottom
StringBuffer: Variable character sequence, thread safe, low efficiency, using StringBuffer when multithreading
                The bottom layer is stored in char []
StringBuilder: Variable character sequence, jdk5 0 is added. The thread is unsafe and efficient. The bottom layer is stored with char []

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

StringBuffer sb1 = new StringBuffer(); // char[] value = new char[16]
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 you want to add data and the underlying array cannot be put down, you need to expand the underlying array!
       The default expansion is twice the original + 2 (value. Length < < 1), and the original array elements are copied to the new array

Meaning: it is recommended to use StringBuffer(int capacity) or StringBuilder(int capacity) in development
 */

public class StringBufferBuilderTest {
    public static void main (String[] args){
        StringBuffer stringBuffer = new StringBuffer("abc");
        stringBuffer.setCharAt(0,'m');
        System.out.println(stringBuffer);//The mbc string has changed

        System.out.println(stringBuffer.length()); //3
    }

}

1.5.3 common methods in StringBuffer

import org.junit.Test;

/**
 * About the use of StringBuffer and StringBuilder
 */
public class StringBufferBuilderTest {

    /**
     * StringBuffer Common methods of:
     *
     * StringBuffer append(xxx): Many append() methods are provided for string splicing
     * StringBuffer delete(int start,int end): Delete the contents of the specified location
     * StringBuffer replace(int start, int end, String str): Replace the [start,end) position with str
     * StringBuffer insert(int offset, xxx): Insert xxx at the specified location
     * StringBuffer reverse() : Reverse the current character sequence
     * public int indexOf(String str)
     * public String substring(int start,int end):Returns a substring of the left closed right open interval from start to end
     * public int length()
     * public char charAt(int n )
     * public void setCharAt(int n ,char ch)
     *
     * Summary:
     *     Add: append(xxx)
     *     Delete: delete(int start,int end)
     *     Change: setcharat (int n, char CH) / replace (int start, int end, string STR)
     *     Check: charAt(int n)
     *     Insert: insert(int offset, xxx)
     *     Length: length();
     *     Traversal: for() + charAt() / toString()
     *
     */
    @Test
    public void test2(){
        StringBuffer s1 = new StringBuffer("abc");
        s1.append(1);
        s1.append('1');
        System.out.println(s1);//abc11
//        s1.delete(2,4);//ab1
//        s1.replace(2,4,"hello");//abhello1
//        s1.insert(2,false);//abfalsec11
//        s1.reverse();// reversal
        String s2 = s1.substring(1,3);
        System.out.println(s1);//s1 unchanged
        System.out.println(s1.length());
        System.out.println(s2);
    }
}

1.5.4 efficiency comparison of string, StringBuffer and StringBuilder

/**
 * About the use of StringBuffer and StringBuilder
 * 
 *      * Compare the efficiency of String, StringBuffer and StringBuilder:
 *      * Arrange from high to low: StringBuilder > StringBuffer > string
 *      *StringBuffer Execution time of: 4
 *       StringBuilder Execution time of: 2
 *         String Execution time: 271
 */
 
public class StringBufferBuilderTest {
    public static void main(String[] args){
        long startTime = 0L;
        long endTime = 0L;
        String text = "";
        StringBuffer buffer = new StringBuffer("");
        StringBuilder builder = new StringBuilder("");
        //Start comparison
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            buffer.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuffer Execution time of:" + (endTime - startTime));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            builder.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuilder Execution time of:" + (endTime - startTime));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            text = text + i;
        }
        endTime = System.currentTimeMillis();
        System.out.println("String Execution time of:" + (endTime - startTime));
    }
    
    }

Topics: Java Back-end