String related classes: String

String class source code

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
String: string, represented by ""
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 string s can compare sizes

 3.string: represents immutable sequence, which is abbreviated as immutable
 Embodiment: 1 When reassigning a string, you need to override the assignment of the specified memory area, and the original value assignment cannot be used
       2. When connecting an existing string, you also need to assign a new value to the memory area. The original value assignment cannot be used
       3. When calling the replace() method of stringd to modify the specified character or string, you also need to reassign the assignment of the memory area

 4. final,char[],value is defined inside string to store string data
 5. Assign a literal value to a string, and the string value is declared in the string constant pool
  6. The string constant pool will not store strings with the same content
Instantiation method of String:
Method 1: defined by literal quantity
 Mode 2: through the new + constructor
public void test2() {
        String s1 = "javaEE";
        String s2 = "javaEE";

        //S3 and S4 store the address value, which is the corresponding address value 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

        Person p1 = new Person("Tom", 21);
        Person p2 = new Person("Tom", 21);

        System.out.println(p1.name.equals(p2.name));//true
        System.out.println(p1.name == p2.name);//true
    }
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=s5.intern();//Return the "Java EE Hadoop" that already exists in the constant value used by s8
        System.out.println(s3 == s8);//true

    }
public void test4(){
         String s1="javaEEhadoop";
         final String s2="javaEE";//constant
         String s3=s2+"hadoop";

         System.out.println(s3==s1);//true
     }

Summary:

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.
As long as one of them is a variable, the result is in the heap
 If the result of splicing calls the intern() method, the return value is in the constant pool
Interview question: how many objects are created in memory by creating objects in String s=new String("abc")?
    Two: one is the new structure in the heap space, and the other is the data in the constant pool corresponding to char []: "abc"

Conversion between string class and other structures

Conversion between String and byte []
String -- > byte []: call getBytes() of string
 Byte [] --- > string: call string constructor
public void test3() throws UnsupportedEncodingException {
       String str1="abc123 Xiao Fan";
       byte[] bytes1=str1.getBytes();//Use the default character set for conversion
       System.out.println(Arrays.toString(bytes1));

       byte[] bytes2 = str1.getBytes("gbk");//Encoding using jbk character set
       System.out.println(Arrays.toString(bytes2));


       String str2=new String(bytes1);
       System.out.println(str2);

       String str3=new String(bytes2,"gbk");
       System.out.println(str3);
   }
[97, 98, 99, 49, 50, 51, -27, -80, -113, -27, -121, -95]
[97, 98, 99, 49, 50, 51, -48, -95, -73, -78]
abc123 Xiao Fan
abc123 Xiao Fan
Conversion between string and char []
String ----- > char []: call string's toCharArray()
Char [] ---- > String: call the constructor of String
public void test2(){
        String s1="abc123";
        char[] charArray=s1.toCharArray();
        for(int i=0;i<charArray.length;i++){
            System.out.print(charArray[i]+" ");
        }

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

Operation results: a b c 1 2 3 hello
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
public void test1(){
        String s1="123";
        //int num=(int)s1;  FALSE
        int num=Integer.parseInt(s1);

        String s2=String.valueOf(num);//"123"
        String s3=num+"";//s3 is in the heap because num is a variable

        System.out.println(s1==s3);//false
    }

String usage trap

String s1 = "a"; Description: a string with literal "a" is created in the string constant pool.

s1 = s1+"b"; Note: in fact, the original "a" string object has been discarded. Now a string s1+"b" (i.e. "ab") is generated in the heap space. If these operations to change the string content are performed multiple times, a large number of copy string objects will be stored in memory, reducing efficiency. If such an operation is placed in a loop, it will greatly affect the performance of the program.

String s2 = "ab"; Description: directly create a string with literal "ab" in the string constant pool.

String s3 = "a" + "b"; Description: S3 refers to the string of "ab" that has been created in the string constant pool.

String s4 = s1.intern(); Note: S1 object in heap space will assign the existing "ab" string in constant pool to S4 after calling intern().

//Interview questions
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
        System.out.println(ex.ch);//best
    }
}
//String has immutability

Common methods of String

 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 substring of this string
 beginIndex starts intercepting the last substring.
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
 String replace(char oldChar, char newChar): returns a new string, which is
 Obtained by replacing all oldchars present 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): use the given
 replacement replaces all substrings of this string that match the given regular expression.
  String replaceFirst(String regex, String replacement): use the given
 replacement replaces this string 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): splits the string based on matching the given regular expression
 String, no more than limit. If it exceeds the limit, all the rest will be placed in the last element.

 

Added by madcat on Mon, 03 Jan 2022 05:30:25 +0200