Understanding of Java String class

Posted by johnc71 on Thu, 10 Feb 2022 11:28:52 +0100

⭐ Preface ⭐ ️

🍉 Blog home page: 🍁 [warm the sun like the wind]🍁
🍉 Boutique Java column [Javase],[Java data structure]
🍉 Welcome to like 👍 Collection ⭐ Message comments 📝 Private letters must be answered 😁

🍉 This article was originally written by [Rufeng Wenyang], and was first launched in CSDN 🙉

🍉 Bloggers will continue to update their learning records. If you have any questions, you can leave a message in the comment area

🍉 The source code involved in the blog and the blogger's daily practice code have been uploaded Code cloud (gitee)

This article is to understand the String class in Java and some of its usage. It may be a long time. The whole article will be completed in distribution.

Learning objectives:

  • Recognize String class
  • Understand the basic usage of String class
  • Familiar with the common operation of String class
  • Recognize string constant pool
  • Know StringBuffer and StringBuilder

Understanding of Java String class

🍉 1. Recognize and create strings

There is no string data type in c language, but there is in Java. What is a string?
It refers to several character constants (or one) enclosed in double quotation marks, and the character is a single character constant caused by single quotation marks. Note: there is no so-called / 0 Peugeot ending as a string in Java.

Common ways to construct String:

// Mode 1
String str = "Hello Bit";
// Mode 2 mode 1 and 2 are essentially the same in the way of constructing String
String str2 = new String("Hello Bit");
// The third way is to change the array into a string
char[] array = {'a', 'b', 'c'};
String str3 = new String(array);

Common pit:

    public static void fun(String str,char[] chars) {
        str="hello";
        chars[0]='A';
    }
    public static void main(String[] args) {
        String str="abcd";
        char[] chars={'c','s','d','n'};
        fun(str,chars);
        System.out.println(str);
        System.out.println(Arrays.toString(chars));
    }
  //: running results
abcd
[A, s, d, n]

We can find that changing the str reference in the fun function does not affect the STR in the main function. This is because both are reference types and the reference object is a constant (it can be changed if the referenced object is a variable), and the constant cannot be changed. Each constant will open up a space, and the STR in fun only points the reference to a new constant, Therefore, the STR in main will not be changed, while the array is accessed through [] conforming to the subscript, which actually changes the data in the array.

🍉 2. String comparison and equality

    public static void main(String[] args) {
        String str1="Hello";
        String str2="Hello";
        String str3=new String("Hello");
        System.out.println(str1==str2);//Code 1
        System.out.println(str1==str3);//Code 2
    }
	//Operation results:
	true
	false


We found that str1 and str2 point to the same object At this time, string constants such as "Hello" are in the string constant pool

About string constant pool
String literal constants such as "Hello" require a certain amount of memory space to store One characteristic of such constants is that they do not need to be modified So if you need to use "Hello" in multiple references in the code, you can directly reference it to the location of the constant pool, instead of storing "Hello" twice in memory


Through String str3 = new String("Hello"); The String object created in this way is equivalent to opening up additional space on the heap to store the contents of "Hello", that is, there is an additional "Hello" in memory.

String using = = comparison is not to compare the string content, but to compare whether two references point to the same object.
To compare the contents of strings in Java, you must use the equals method provided by the String class.

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2));
// System.out.println(str2.equals(str1)); //  Or it can be written like this
// results of enforcement
true

Because str1, str2 and str3 are all reference types, but why are there two different answers? Next, let's explore their distribution in memory in 3 and get the reason for the results.

🍉 3. String constant pool and manual pool entry

String constant pool

You may be unfamiliar with this concept. Let's first talk about what a pool is -
Pool is a way for us to improve efficiency in programming. It's just like the food cooked in a restaurant. We can buy it and eat it directly. We don't have to cook it ourselves. If we don't have what we want to eat, we can cook it ourselves.
String constant pool is a pool used to store string constants (located in the heap). Its essence is a hash table used to store string constants enclosed in double quotes.
Hash table is a data structure (the way to describe and organize data). It is a combination structure that stores strings in multiple linked lists based on array structure through a mapping relationship.

Entering the String source code, we can find that there are two parameters inside it, one is array (used to convert the String into array form and then store), and the other is hash (used to store the hash value of the String)
String source code:

String type memory condition:

When constructing a string constant, if the string is constructed for the first time, it will enter the string constant pool, in which the relevant data of the string will be stored (the string can be found through this data, as shown in the figure below). The purple node in the figure below is the connection hub, which is also a node of the linked list.

Code 1:

This is the memory distribution of code 1. Because there is a string constant "Hello" in the pool, str2 can directly point to the string type pointed to by str1. If they point to the same space, str1==str2.

Code 2:

Code 2 is because str3 creates a new "Hello" object. Although it already exists in the constant pool, it opens up another space, so str1= Str3, but their val points to the same space.

Common errors:
(1)

    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "he"+"llo";//At this time, both of them are constants. When compiling, it has been determined to be "hello"
        String str3 = "he";
        String str4 = str3+"llo";//At this time, str3 is a variable - I don't know what it is when compiling?
        System.out.println(str1 == str2);
        System.out.println(str1 == str4);
    }
    //: 
true
false

In the first case, it has been determined at compile time, so they are the same. In the second case, new objects are generated.
(2)

    public static void main(String[] args) {
        String str1 = "11";
        String str2 = new String("1")+new String("1");
        System.out.println(str1 == str2);
    }
    //
    false

The "11" spliced by str2 code is a new object, so they are not equal

Manual pool entry

In (2) of the above common errors, the code is slightly modified

    public static void main(String[] args) {
        String str2 = new String("1")+new String("1");
        str2.intern();//Manual pool entry
        String str1 = "11";
        System.out.println(str1 == str2);
    }
    //true

Why is the result different when there is one more line of code? This is because the string constant exists in the string constant pool after the two string constants "1" are spliced into a new string "11".

But pay attention to the code order. Only when there is no string constant pool will it enter the pool

    public static void main9(String[] args) {
        String str1 = "11";
        String str2 = new String("1")+new String("1");
        str2.intern();//Enter the pool manually - when there is no string constant pool, it will enter the pool
        System.out.println(str1 == str2);
        System.out.println(str1.equals(str2));
    }
    //false

🍉 4. The string is immutable

A String is an immutable object Its content cannot be changed. The internal implementation of String class is also based on char [] (and it is private and inaccessible outside the class). However, String class does not provide set method to modify the internal character array, so its content cannot be changed.
Feel the following code:

String str = "hello" ; 
str = str + " world" ; 
str += "!!!" ; 
System.out.println(str); 
// results of enforcement
hello world!!!

Operations like + =, on the surface, seem to modify the string. In fact, it is not. After splicing into a new string, the str reference points to the new string.
If you really want to change the string constant, you can only do it through reflection, which we will learn later.

⚡ Last words ⚡ ️

Unfinished to be continued——
It's not easy to summarize. I hope uu you won't be stingy with your work 👍 Yo (^ u ^) yo!! If you have any questions, please comment and correct them in the comment area 😁

Topics: Java Back-end JavaSE