Advanced Java programming -- common Java classes -- String related classes -- String

1, Properties of the String class

  • The String class represents a String. All String literals (such as "abc") in Java are used as the implementation classes of this class

  • The String class is a final class, which represents immutable characters and cannot be inherited

  • A string is a constant, expressed in double quotation marks. Their values cannot be changed after wiping the yellow key.

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

  • String implements the Serializable interface: it means that the string supports serialization

  • The Comparable interface is implemented: it means that strings can compare sizes

  • String internally defines final char[] value to store character data

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

1.1 immutability of string

  • String: represents an immutable character sequence. The abbreviation is not changeable.

reflect:

① : when the string is re assigned, the memory area needs to be re assigned. The original value cannot be used for assignment
② : when connecting an existing string, you also need to assign a value to the memory area again. You cannot assign a value to the original value
③ : when calling the replace method of String to modify the specified String or character, you also need to re specify the memory area assignment, which cannot be assigned on the original value

@Test

    @Test
    public void  test1(){
        //Here s1\s2 share an "abc"
        String s1 = "abc";//Literal definition,
        /*
        s1 "abc" is used for the first time, and "abc" is directly generated in the string constant pool in the method area
        And assign the first address value of "abc" to s1
         */

        String s2 = "abc";
        /*
        There will not be two identical strings in the constant pool, so the "abc" obtained by s2 here is the same as that obtained by s1

         */


        String s3 = "abc";
        s3 += "def";
        System.out.println(s3 == s2);//false
        /*
        The splicing operation of s3 here is to create another string in the string constant pool
         */


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

    }

output

false
abc
mbc
false

1. Different instantiation methods of 2String (creation of String object)

1.2.1

        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 s1 = “abc”; And String s2 = new String("ABC"); Differences between

    @Test
    public void Test2(){
        /*
        String Instantiation method of
        Method 1: defined by literal quantity
        Mode 2: through the new + constructor
         */


        //Literal definition: the address value at this time is the only address value in the string constant pool in the method area
        String s1 = "hello";
        String s3 = "hello";

        //new: the address value at this time is the corresponding address value after the data opens up space in the heap space
        String s2 = new String("hello");
        String s4 = new String("hello");

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

1.2.2.2 Test2() memory analysis

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

1.3 String comparison of different splicing operations

code

    @Test
    public  void Test3(){
        /*

         */
        String s1 = "java";
        String s2 = "ee";

        String s3 = "javaee";
        String s4 = "java" + "ee";
        String s5 = s1 + "ee";
        String s6 = "java" + 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

    }
    

Output:

true
false
false
false
false
false
false

If you add another instantiated object s8, use the following method: String s8 = S5 intern();
At this time, the result of output (s3 == s8) will return true; Because the address value returned at this time is the address value of the constant in the constant pool

Conclusion:

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

Only one of them needs to be a variable, and the result is in the heap

If the result of splicing calls the intern() method, the return value is in the constant pool

2, Methods in String

2.1 String common method I

2.1.1 length()

Function: return string length
Return value type: int

        //int length(): returns the length of the string
        String s1 = "hello world";
        System.out.println(s1.length());

Output:

11

2.1.2

Function: returns the character at an index
Return value type: char

        //char charAt(int index) returns the character at an index. return value[index]
        System.out.println(s1.charAt(2));

Output:

l

2.1.3 isEmpty()

Function: judge whether the current string is an empty string
Return value type: boolean

        //boolean isEmpty() determines whether the current string is an empty string return value length == 0;
        System.out.println(s1.isEmpty());

Output:

false

2.1.4 toLowerCase(),toUpperCase()

Function: make the current string small / uppercase
Return value type: String

		String s1 = "HEllO world";
        //String toLowerCase() lowercase the current string
        System.out.println(s1.toLowerCase());
         //String toUpperCase() capitalizes the current string
        System.out.println(s1.toUpperCase());
        System.out.println(s1);

Output:

hello world
HELLO WORLD
HEllO world

Here again, the immutability of String is reflected

2.1.5 trim()

Action: returns a copy of the current string ignoring leading and trailing whitespace
Return value type: String

        //String trim() returns a copy of the current string ignoring leading and trailing whitespace
        String s2 = "  h e  l l o";
        String s3 = s2.trim();
        System.out.println("***"+s3+"***");
        System.out.println("***"+s2+"***");

Output:

***h e  l l o***
***  h e  l l o***

2.1.6 equals(),equalsIgnoreCase

Function: compare whether two strings are the same. equalsIgnoreCase() ignores case
Return value type: boolean

        //boolean equals(Object obj) compares whether two strings are the same
        System.out.println(s1.equals(s2));//false

        String s4 = "hello";
        String s5 = "HEllo";
        System.out.println(s4.equalsIgnoreCase(s5));//true

Output:

false
true

See the previous article for details on using equals

2.1.7 concat(String str)

Function: connect the specified string to the end of this string, which is equivalent to "+"
Return value type: boolean

        //boolean concat(String str): connects the specified string to the end of the string, which is equivalent to "+"
        String str1 = "hello  ";
        String str2 = "nicky";
        System.out.println(str1.concat(str2));

Output:

hello  nicky

2.1.8 compareTo(String anotherString)

Function: compare the size of two strings (involving string sorting)
Return value type: int

        //Int CompareTo (string otherstring) compares the size of two strings
        str1 = "abc";
        str2 = "abd";
        System.out.println(str1.compareTo(str2));

Output: (a negative number indicates that the current character is small, 0 indicates equal, and a positive number indicates that the current character is large)

-1

2.1.9 substring(int beginIndex),substring(int beginIndex,int endIndex)

Function: substring(int beginIndex) returns a new string truncated from the beginIndex of the current string, and substring(int beginIndex,int endIndex) returns a string from the current character position beginIndex to the position endIndex
Return value type: String

        //String substring(int beginIndex): returns a new string truncated from the beginIndex of the current string,
        str1 = "I love China!";
        System.out.println(str1.substring(1));
         System.out.println(str1.substring(0, 6));//Include characters on beginIndex, but not characters at endIndex position

Output:

 love China!
I love

2.2 String common method 2

2.2.1 endWith,startsWith

Function: endWith(String suffix): test whether the string ends with the specified suffix, case sensitive
startsWith(String prefix): test whether the string starts with the specified prefix and is case sensitive
startsWith(String prefix,int toffset): tests whether the substring of this string starting from the specified index starts with the specified prefix
Return value type: boolean

        //boolean endWith(String suffix) tests whether the string ends with the specified suffix and is case sensitive

        String str1 = "I love China!";
        System.out.println(str1.endsWith("a"));//false
        System.out.println(str1.endsWith("!"));//true


        //boolean startsWith(String prefix) tests whether the string starts with the specified prefix and is case sensitive
        System.out.println(str1.startsWith("a"));//false
        System.out.println(str1.startsWith("i"));//false
        System.out.println(str1.startsWith("I"));//true

        //boolean startsWith(String prefix,int toffset) tests whether the substring of this string starting from the specified index starts with the specified prefix
        System.out.println(str1.startsWith("l", 2));//true
        System.out.println(str1.startsWith("a", 5));//false

Output:

false
true
false
false
true
true
false

2.2.2 contains

Function: returns true if and only if this string contains the specified char value sequence
Return value type: boolean

        //Boolean contains (charsequences) returns true if and only if this string contains the specified char value sequence
        String str1 = "I loce China!";
        System.out.println(str1.contains("China"));//true
        System.out.println(str1.contains("H"));//false

Output:

true
false

2.2.3 IndexOf,lastIndexOf

effect:
indexOf(String str): returns the index of the first occurrence of the specified substring in this string
indexOf(String str,int fromIndex): returns the index of the first occurrence of the specified string starting from the specified index
lastIndexOf(String): returns the index of the last occurrence of the specified string in this string
lastIndexOf(String str,fromIndex): returns the index of the last position in the specified substring before the specified index
Return value type: int (return index found, return - 1 not found)

		String str1 = "I love China!";
        //int indexOf(String str) returns the index of the specified substring at the first occurrence in this string
        str1 = "my name is Lisa";
        System.out.println(str1.indexOf("a"));//4
        System.out.println(str1.indexOf("A"));//-1 case sensitive


        //int indexOf(String str,int formIndex) returns the first occurrence of the specified string from the specified index
        System.out.println(str1.indexOf("a", 2));//4
        System.out.println(str1.indexOf("L", 11));//11
        System.out.println(str1.indexOf("y", 6));//-1

        //int lastIndexOf(String str) returns the last index of the specified substring in this string
        System.out.println(str1.lastIndexOf("a"));//14
        System.out.println(str1.lastIndexOf("H"));//-1

        //int lastIndexOf(String str, int formIndex) returns the index of the last place in the specified string before the specified index
        System.out.println(str1.lastIndexOf("Y",10));//-1
        System.out.println(str1.lastIndexOf("a",7));//4

Output:

4
-1
4
11
-1
14
-1
-1
4

indexOf and lastIndexOf methods are not found. Both return - 1

2.3 three common methods of string

2.3.1 replace

effect:
String replace(char oldChar,char newChar): returns a new string, which is obtained by replacing all oldchars in the string with newChar
String replace(CharSequence target,CharSequence replacement): replaces all substrings in this string that match the literal target sequence with the specified literal replacement sequence
Return value type: string (a new string will be returned if the replacement succeeds, and the original string will be returned if the replacement fails)

        //String replace(char oldChar,char newChar): returns a new string, which is obtained by replacing all oldchars in the string with newChar
        String str1 = "I love my country,and I love my hometown.";
        System.out.println(str1.replace('I', 'i'));//"i love my country,and i love my hometown."
        System.out.println(str1.replace('i', 'I'));//"I love my country,and I love my hometown."

        //String replace(CharSequence target,CharSequence replacement): replaces all substrings in this string that match the literal target sequence with the specified literal replacement sequence
        System.out.println(str1.replace("love", "like"));//"I like my country,and I like my hometown."
        System.out.println(str1.replace("LOVE", "like"));//"I love my country,and I love my hometown."

Output:

i love my country,and i love my hometown.
I love my country,and I love my hometown.
I like my country,and I like my hometown.
I love my country,and I love my hometown.

2.3. Methods involving regular expressions (not understood yet)

  • replaceAll(String regex,String replacement)
    Function: use the given replacement to replace all strings matching the given regular expression in this string
    Return value type: String

  • replaceFirst(String regex,String replacement)
    Function: use the given replacement to replace the first string in this string that matches the given regular expression
    Return value type: String

  • matches(String regex):
    Function: tells whether this string matches a given regular expression
    Return value type: boolean

  • split(String regex)
    Function: splits the string according to the matching of the given regular expression
    Return value type: String []

  • split(String regex,int limit)
    Function: split the string according to the matching given regular expression. The maximum number is no more than limit. If it exceeds, all the rest will be placed in the last element
    Return value type: String []

3, String to another data type

3.1 conversion between string and char arrays

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

    @Test
    public void Test4(){

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

        System.out.println(new String(str1));

    }

Output:

a
b
c
1
2
3
abc123

3.2 conversion between string and byte []

String – > byte []: call getBytes() of string - encoding
byte [] – > String: call the constructor of String - decode
code:

        String str = "abc123 China";
        byte[] bytes = str.getBytes();//Use default character set conversion
        System.out.println(Arrays.toString(bytes));

        byte[] gbks = str.getBytes("gbk");//Use gbk character set encoding (string -- > bytes)
        System.out.println(Arrays.toString(gbks));

Output:

[97, 98, 99, 49, 50, 51, -28, -72, -83, -27, -101, -67]
[97, 98, 99, 49, 50, 51, -42, -48, -71, -6]

decode:
*When decoding, it is required that the decoding set is consistent with the encoding set, otherwise there will be garbled code in decoding*

        String str = "abc123 China";
        
        byte[] bytes = str.getBytes();//Use default character set conversion
        byte[] gbks = str.getBytes("gbk");//Use gbk character set encoding (string -- > bytes)

        System.out.println(new String(bytes));//Call the constructor of String to decode the default encoding
        System.out.println(new String(gbks));//jbk is used for encoding, but utf-8 is used for decoding here, resulting in garbled code
        System.out.println(new String(gbks, "gbk"));//Decode using the specified encoding set
        

Output:

abc123 China
abc123�й�
abc123 China

3.2 conversion between string, basic data type and packing class

See blog

Keywords: Java

Added by jeff_lawik on Sat, 18 Dec 2021 11:20:46 +0200