Commonly used classes (1) String

1. The characteristics of String

String class : represents a string

String is a final class that represents an immutable sequence of characters . Not inheritable

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

From the source code, you can see that the String class implements the Serializable, Comparable, and CharSequence interfaces. Comparable is implemented to indicate that String can be compared in size, and CharSequence is implemented to indicate that String can operate on a series of character methods. All of the CharSequence interfaces are some methods.

Among them, the array value[] is also final. After the array is assigned, its address cannot be modified because it is finalized. The array cannot be re-assigned, and the value of the element cannot be modified , indicating that the String is not A sequence of characters that can be changed.

Why is String immutable?

Simple code demonstration and analysis:

import org.junit.Test;

public class StringMain {
    @Test
    public void test01(){
        String str1 = "123";
        String str2 = "123";
        str1="hello";
        System.out.println(str1==str2);
    }
}

Output: true

Analysis: The method area contains a string constant pool, in different jdk, the division is not the same, the latest is in the heap.

Assign a value to a string literally. At this time, the string value will be declared in the string constant pool  , and there will be no strings with the same content in the string constant pool.

Because our String is saved using the final [] value, now str1 has been assigned the value 123. We are assigning the value hello to str1, instead of directly modifying the 123 of the constant pool, we recreate a hello one. There is no right Modify the previous value (123)

So reflect immutability:

1. When re-assigning a string, it is necessary to re-assign the memory area for assignment, and the original value cannot be used for assignment

2. When concatenating an existing string, you also need to re-specify the memory area for assignment, and you cannot use the original value for assignment

3. When you modify the character when calling replace(), you also need to re-specify the memory area assignment, you cannot use the original value for assignment

If you have any doubts, you can check the address of str1:

import org.junit.Test;

public class StringMain {
    @Test
    public void test01(){
        String str1 = "123";
        System.out.println(System.identityHashCode(str1));
        String str2 = "123";
        str1="hello";
        System.out.println(System.identityHashCode(str1));
        System.out.println(str1==str2);
        final int []value;
    }
}

Output content:

1456208737
288665596
false

Creation of String object

View the screenshot of the creation of the String object of the source code:

What is the difference between String str1 = "abc" and String str2 = new String("abc")?

First look at the source code of newString(str):

 @HotSpotIntrinsicCandidate
    public String(String original) {
        this.value = original.value;
        this.coder = original.coder;
        this.hash = original.hash;
    }

Since the object is created by the new method, it is to open up space in the heap. The diagrams of the two are:

If there is no one in the constant pool, one will be recreated, and others will not be modified.

Look at the true/false question again: attach a diagram to explain

Summary :

1. The splicing result of the constant and the constant is in the constant pool. And there will be no constants with the same content 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

2. String commonly used methods

Method prototype Meaning function
int length() Returns the length of the string
char charAt(int index) Returns the character at an index
boolean isEmpty() Determine whether it is an empty string
String toLowerCase() Convert all characters in String to lowercase
String toUpperCase() Convert all characters in String to uppercase
String trim() Returns a copy of the string, ignoring leading and trailing whitespace
boolean equals(Object obj): Compare whether the contents of the string are the same
boolean equalsIgnoreCase(String anotherString) Similar to the equals method , ignoring case
String concat(String str) Concatenate the specified string to the end of this string. Equivalent to using "+"
int compareTo(String anotherString) Compare the size of two strings
String substring(int beginIndex) Returns a new string, which is a substring of this string that is intercepted from beginIndex to the end.
String substring(int beginIndex, int endIndex) Return a new string, which is a substring of this string from beginIndex to endIndex (not included)
boolean endsWith(String suffix) Test whether this string ends with the specified suffix
boolean startsWith(String prefix) Test whether this string starts with the specified prefix
boolean startsWith(String prefix, int toffset) Test whether the substring of this string starting from the specified index starts with the specified prefix
boolean contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values
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, searching backwards from the specified index
String replace(char oldChar, char newChar) Return a new string, which is obtained by replacing all oldChar occurrences in this string with newChar
String replaceAll(String regex, String replacement) Use the given replacement to replace all substrings of this string that match the given regular expression.
boolean matches(String regex) Tell whether this string matches the given regular expression.
String[] split(String regex) Split this string according to the match of the given regular expression

The indexOf and lastIndexOf methods both return -1 if not found 

3. String and basic data type conversion

     1, the string into  the basic data types, packaging

      1) The public static int parseInt(String s ) of the Integer wrapper class : it can convert a string composed of "digital" characters into an integer.

     2) Similarly, use the Byte, Short, Long, Float, and Double classes in the java.lang package to adjust the corresponding class methods to convert the string composed of "digital" characters into the corresponding basic data type

     2, the basic data types, and packaging into a string

调用String类的public String valueOf(int n)将int型转换为字符串 valueOf(byte b)、valueOf(long l)、valueOf(float f)、valueOf(double d)、valueOf(boolean b)可由参数的相应类型到字符串的转换。

     3、字符数组 转为 字符串

String 类的构造器:String(char[]) 和 String(char[],int offset,int length) 分别用字符数组中的全部字符和部分字符创建字符串对象

     4、字符串 转为 字符数组

public char[] toCharArray():将字符串中的全部字符存放在一个字符数组 中的方法

Guess you like

Origin blog.csdn.net/weixin_43725517/article/details/112794014