I am learning Java in VScode (Java string)

My personal blog homepage: If "" can really escape 1️⃣ say 1️⃣ blog homepage
about Java basic grammar learning ----> you can refer to my blog: "I learn Java in VScode"
about Java array learning, JVM The heap and stack —> You can refer to my article I learn Java in VScode (Java one-dimensional array, two-dimensional array, heap and stack in JVM) remake

Article directory

java_string

In Java, String is a class defined in the java.lang package. Therefore, the String class can be used without making an import statement.

Create (direct assignment, new one)

To create a Java String, you can use one of the following methods:

1. Use string literals to create (string pool – direct assignment to obtain a string object):

 String str = "Hello, World!";

Directly use the string literal to assign to the variable str. This method first checks whether there is a string object with the same content in the string constant pool 1, and if it already exists, directly refers to the object; if it does not exist, creates a new string object in the constant pool . This saves memory space and avoids repeated creation of string objects with the same content.

Literal:

Literals are a special grammatical form for representing values, which can represent different types of data, such as strings, numbers, Boolean values, etc. In Java, literals are identified by classes.

For different types of literals, the Java compiler will convert them into objects of corresponding types according to the grammar rules.

  • String literals are converted to String objects, identified by the String class.
  • Numeric literals can be converted into objects of different types according to the specific value range and representation. For example, integer literals may be converted into objects of types such as int and long.
  • Boolean literals can be converted to Boolean objects, identified by the Boolean class.

No matter what type of data the literal represents, the object will be determined through the corresponding class eventually, and the corresponding value will be assigned to the object.

It should be noted that the literal itself is not an object, but a syntactic representation representing a specific value. During compilation, the compiler will generate corresponding objects or constants according to the type of literals, and include them in the code for program use.

String literals are converted to String objects, identified by the String class. What is the conversion process:

In Java, the compiler converts a string literal into a String object as follows:

  1. When we use a string literal enclosed in double quotes in the code, for example: "Hello, World!", the compiler will first check whether a string with the same content already exists in the string constant pool (String Pool).

  2. If there is no string with the same content in the string constant pool, the compiler will create a new string object in the string constant pool, and store the content of the string literal in the character array of the new object.

  3. If a string with the same content already exists in the string constant pool, the compiler will directly return a reference to the corresponding string in the string constant pool.

  4. Whether creating a new String object or returning a reference to an existing String, the result is assigned to a variable or expression of type String.

To sum up, the conversion process of creating a String object through a string literal mainly includes two steps of searching in the string constant pool and creating the object. If there is no string with the same content in the string constant pool, a new string object will be created; if there is a string with the same content, the corresponding string reference will be returned directly. Finally, we can refer to this converted String object through a variable of String type.

Two, new one (heap memory)

Construct a string object with empty parameters

Created using the String keyword and constructor:

在Java中,空白可以用空字符串("")来表示。在给定的代码中:
String s = new String();
System.out.println(s); // 
System.out.println(s.hashCode());//0
System.out.println(s.equals(""));//true
空串“”是长度为0的字符串:是Java的一个对象

```java
if(str.length()==0)
或者:
if(str.equals(""))
或者:
isEmpty()方法

while Null is a special value

if(str==null)
if(str!=null&&str.length()!=0)
the difference:

Although there are no characters in a string of length 0, it is still a valid string object.
And null is an object that has not been instantiated, or does not point to any valid memory address

obj是需要判断的对象。如果obj为NULL,则执行do something中的代码。否则,不执行任何操作。
if (obj == null) {
    
    
    // do something
}
null串。
	这个对象可以是任何类型的对象,包括字符串、数组、类等等。当一个对象被赋值为null时,
它就不再指向任何对象,也就是说它不再引用任何对象,因此也就无法访问该对象的任何属性或方法。
##### 传递了一个字符串,相当于传递了一个字符串的对象
 [使用new关键字创建的字符串对象则会在堆内存中进行分配。]
```java
    String str = new String("Hello, World!");

Use the constructor to create a string object and assign the string content to the variable str. This method will create a new string object in the heap memory, regardless of whether a string with the same content already exists in the original string constant pool. Even if a string object with the same content exists, a new one is created. This will take up more memory space.
Strings are immutable (immutable) objects. In most cases, it is more efficient and recommended to directly use string literals to create string objects, while using new String() is mainly used for specific business needs or for character The case where a copy of a string constant is modified.

other
'=='比较

The basic data type compares ---- data value
The reference data type compares ---- address value

// 字符串比较
String str1 = "aaa"; // 创建一个字符串变量str1并赋值为"aaa"
String str2 = "aaa"; // 创建一个字符串变量str2并赋值为"aaa"
System.out.println(str1 == str2); // 使用"=="比较两个字符串的引用,输出结果为true
System.out.println(str1.equals(str2)); // 使用equals()方法比较两个字符串的内容,输出结果为true
String str3 = new String("aaa"); // 创建一个新的字符串对象str3,并赋值为"aaa"

System.out.println(str1 == str3); // 使用"=="比较str1和str3的引用,输出结果为false
System.out.println(str1.equals(str3)); // 使用equals()方法比较str1和str3的内容,输出结果为true

byte[] bytes = {
    
     97, 97, 97 }; // 创建一个字节数组bytes,包含三个字节97(对应ASCII码中的字符'a')
String str4 = new String(bytes); // 使用字节数组创建一个新的字符串对象str4,值为"aaa"
System.out.println(str4 == str3); // 使用"=="比较str4和str3的引用,输出结果为false
System.out.println(str4.equals(str3)); // 使用equals()方法比较str4和str3的内容,输出结果为true

System.out.println(str4 == str2); // 使用"=="比较str4和str2的引用,输出结果为true
System.out.println(str4.equals(str2)); // 使用equals()方法比较str4和str2的内容,输出结果为true

Scanner sc = new Scanner(System.in); // 创建一个Scanner对象sc,用于接收用户输入

String str5 = sc.nextLine(); // 从用户输入中读取一行字符串aaa,并赋值给str5
System.out.println(str1 == str5); // 使用"=="比较str1和str5的引用,输出结果为false
System.out.println(str1.equals(str5)); // 使用equals()方法比较str1和str5的内容,输出结果为true

String str6 = sc.next(); // 从用户输入中读取一个字符串aaa,并赋值给str6
System.out.println(str1 == str6); // 使用"=="比较str1和str6的引用,输出结果为false
System.out.println(str1.equals(str6)); // 使用equals()方法比较str1和str6的内容,输出结果为true

sc.close(); // 关闭Scanner对象sc

Among these methods, the first method is the most commonly used, and a String object can be created by directly using a string literal enclosed in double quotation marks.

Compared:

call directly

In Java, string literals can be directly assigned to variables of type String without using the new keyword to create a new string object. This is because Java does special handling of string literals and automatically stores them in a memory area called the "string constant pool". When multiple String objects are created with the same string literal, they actually refer to the same String object in the constant pool. This optimization mechanism can save memory space and improve the efficiency of string comparison.
The benefits of this optimization mechanism are:

Save memory space: Since the string object in the string constant pool is unique, only one copy of the string with the same content needs to be stored in the constant pool.
Improve the efficiency of string comparison: Since strings with the same content share the same object, you can judge whether they are equal by reference comparison without comparing characters one by one, which improves the efficiency of comparison.
It should be noted that this optimization only applies to string literals, not to string objects created using the new keyword. String objects created using the new keyword will be allocated space in the heap memory separately, and will not be placed in the string constant pool.
Therefore,
in your code, both str1 and str2 point to the same "aaa" string object in the string constant pool, so str1 can be called directly without using the new keyword to create a new object.

new:

When a keyword is used newto create a string object, space will be allocated for the string in the heap memory alone, and objects in the string constant pool will not be shared. This means that every time you newcreate a string object with a keyword, you get a new, independent string object.

For example:

String str1 = new String("aaa");
String str2 = new String("aaa");

In the above code, str1and are two new string objects created str2using keywords respectively , and their contents are both "aaa", but they are two separate objects in memory. newEven though the contents of two strings are the same, their references are different.

The use newof CreateString objects typically occurs in scenarios where the contents of a string need to be constructed dynamically, such as from user input or other runtime data. It should be noted that since the string objects created by keywords will not share the objects in the string constant pool, methods should be used instead of simple reference newcomparisons when performing string comparisons .equals()

In short, newthe string object created by keyword exists independently in the heap memory and is not shared with the object in the string constant pool, which is suitable for the situation where the content of the string needs to be dynamically constructed.

Where is the quote from and where is it at the end

A reference is a variable or object that refers to a location in memory. In Java, when we declare a variable of reference type, we actually create a variable in the stack memory and point the variable to the object in the heap memory.

For example:

String str = "Hello";

In this example, stra variable of type reference. In the stack memory, a strvariable named is created, and this variable holds the address (or reference) of the string "Hello" in the heap memory. The string object stored in the heap memory can be accessed through this reference.

When we newcreate a string object through a keyword, Java will allocate a space in the heap memory to store the object and return its address (reference) to us.

For example:

String str = new String("World");

In this example, newa string object "World" is created using the keyword, and the address of the object is assigned to a variable str. Now the variable strpoints to the string object "World" in the heap memory.

It should be noted that a reference itself is just an address pointing to an object and occupies relatively little space in stack memory. The actual object data is stored in the heap memory, occupying a larger memory space.

To sum up, references are kept in stack memory and used to point to objects in heap memory. Object data in heap memory can be accessed and manipulated by reference.

important point:

String concatenation produces a new string, that is, three strings during the running of the following code

String hello="hello";
String world="world";
Sout(hello+world)

If the content of the original variable is changed, a new string is still created (ie: cannot be changed after creation)

In most programming languages, strings are immutable data types, which means that once a string is created, its contents cannot be changed. When we make changes to a string, we actually create a new string object, and the original string object is not modified.
This is because the memory space of the string is allocated statically (a fixed space is allocated in memory), and once the space is allocated, its size or content cannot be changed. Therefore, any change to the string content requires the creation of a new string object to store the changed content.

String hello="hello";
hello ="hello world";

In computer memory, each variable is allocated a certain amount of space. For a variable of string type, it needs a continuous memory space to store the content of the string. When we create a string variable, the computer will allocate a certain amount of memory space for the string. This space is statically allocated, which means that the size of this space is fixed and cannot be changed dynamically.

Therefore, when we change the content of a string variable, we actually create a new string object instead of directly changing the string content in the original memory space. Because the originally allocated memory space has a fixed size and cannot be expanded or reduced. So, any change to the string content requires the creation of a new string object to store the changed content. This is why strings are immutable data types.

What is, can be spliced ​​with '+'

Before JDK8, the string splicing operation will indeed automatically create an StringBuilderobject through the bottom layer of the system, and call its append()method to complete the splicing. After splicing is complete, call toString()the method to StringBuilderconvert the object into Stringa type. In toString()the underlying implementation of the method, keywords will be used to newcreate a new string object to store the final splicing result.
In the JDK8 version and later, the JVM will directly allocate a character array to store the content to be spliced ​​according to the estimated total size after splicing, and perform the splicing operation. This avoids frequent creation and destruction of temporary objects during splicing StringBuilder. A new string object is only generated when doing an explicit string-to- Stringtype conversion or calling a specific Stringclass method (for example ).toUpperCase()

The JDK8 version introduces Compact Stringsthe feature based on byte array, which uses byte array to store string data, saves memory space and improves performance. This optimization method also makes string concatenation more efficient.

The following are common string handling methods in Java:

  1. String concatenation:
    • Use the "+" sign to concatenate the two strings.
    • Use concat()method to concatenate two strings.
  // 字符串连接
        String str1 = "Hello";
        String str2 = "World";
        String concatenationResult1 = str1 + " " + str2;
        String concatenationResult2 = str1.concat(' ' + str2);
                                    //str1.concat(" ").concat(str2);
        System.out.println("字符串连接结果:" + concatenationResult1);//字符串连接结果:Hello World
        System.out.println(concatenationResult2);//字符串连接结果:Hello World
  1. String interception:
    • Use substring()the method to get a substring from a string.
   // 字符串截取
        String originalString = "Hello World";
        String substring = originalString.substring(6);
        System.out.println("截取子字符串:" + substring);//截取子字符串:World
  1. String comparison:
    • Use equals()method to compare two strings for equality.
   -     // 字符串比较
        String string1 = "Hello";
        String string2 = "Hello";
        boolean isEqual = string1.equals(string2);
System.out.println("字符串比较结果:" + isEqual);
  • Use compareTo()the method to compare the magnitude relationship of two strings.

  • 
       // 定义字符串变量
       String str1 = "apple";
       String str2 = "banana";
    
       // 使用compareTo()方法比较两个字符串的大小关系
       int result = str1.compareTo(str2);
    
       // 输出比较结果
       if (result < 0) {
          
          
           System.out.println("str1 小于 str2");
       } else if (result > 0) {
          
          
           System.out.println("str1 大于 str2");
       } else {
          
          
           System.out.println("str1 等于 str2");
       }```
    
    
  • equalslgnoreCase (string to compare) Ignore case comparison

.== sign comparison

 //基本数据类型:比的是数据值
  //引用数据类型: 比的是地址值

insert image description here

To compare content use equals

  1. String split:
    • Use split()the method to split a string into multiple substrings.
        // 字符串分割
        String sentence = "Java is a programming language";
        String[] words = sentence.split(" ");
        System.out.println("分割后的字符串数组:");
        for (String word : words) {
    
    
            System.out.println(word);
        }
  1. String replacement:
    • Use replace()method to replace a certain substring in a string with another string.

        // 字符串替换
        String originalSentence = "I love apples";
        String replacedSentence = originalSentence.replace("apples",
                "oranges");
        System.out.println("替换后的字符串:" + replacedSentence);
    }
}
  1. String case conversion:
    • Use toUpperCase()the method to convert all characters in the string to uppercase.
    • Use toLowerCase()the method to convert all characters in the string to lowercase.
        // 字符串大小写转换
        String lowercaseString = "hello world";
        String uppercaseString = lowercaseString.toUpperCase();
        System.out.println("转换为大写字母:" + uppercaseString);

  1. String conversion:
    • Use valueOf()methods to convert other data types to strings.
    • Use parseXxx()methods to convert strings to other data types.
    // 字符串转换
        int number = 42;
        String numberString = String.valueOf(number);
        System.out.println("转换为字符串:" + numberString);

  1. String formatting:
    • Use String.format()methods to format data into a specific string form.
        // 字符串格式化
        String formattedString = String.format("The value of PI is approximately %.2f", Math.PI);
        System.out.println("格式化后的字符串:" + formattedString);
  1. String lookup:
    • Use indexOf()the method to find the position of a specified character or substring in a string.

        // 字符串查找
        String phrase = "Java programming language";
        int index = phrase.indexOf("programming");
        System.out.println("'programming'第一次出现的位置:" + index);
  • Use lastIndexOf()the method to find the position of a specified character or substring in a string.
  1. String judgment:
    • Use startsWith()the method to determine whether the string starts with the specified prefix.
   // 字符串判断
    String startsWithExample = "Hello World";
    boolean startsWithHello = startsWithExample.startsWith("Hello");
    System.out.println("是否以'Hello'开头:" + startsWithHello);
- 使用`endsWith()`方法判断字符串是否以指定的后缀结尾。
  1. String to remove spaces:
    • Use trim()the method to remove spaces from both ends of the string.
        // 字符串去除空格
        String stringWithSpaces = " Trim me ";
        String trimmedString = stringWithSpaces.trim();
        System.out.println("去除空格后的字符串:" + trimmedString);
  1. String to char array:
    • Use toCharArray()the method to convert a string to a character array.
    // 字符串转换为字符数组
        String word = "Java";
        char[] charArray = word.toCharArray();
        System.out.println("字符数组:");
        for (char c : charArray) {
    
    
            System.out.println(c);
        }
  1. String format validation:
    • Use regular expressions and matches()methods to verify that a string conforms to specific format requirements.

        // 字符串格式验证
        String email = "[email protected]";
        boolean isValidEmail = email
                .matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
        System.out.println("是否是有效的邮箱地址:" + isValidEmail);

  1. String repeats:
    • Use repeat()the method to repeat a string a specified number of times.

// String repeatedString
repeatedString = "Java".repeat(3);
System.out.println("Repeated String: " + repeatedString);
}

other:

public class StringFunctionsExample {
    
    
    public static void main(String[] args) {
    
    
        // 字符串比较
        String str1 = "aaa";
        String str2 = "aaa";
        System.out.println(str1 == str2);
        System.out.println(str1.equals(str2));
        String str3 = new String("aaa");

        System.out.println(str1 == str3);
        System.out.println(str1.equals(str3));

        byte[] bytes = {
    
     97, 97, 97 };

        String str4 = new String(bytes);
        System.out.println(str4 == str3);
        System.out.println(str4.equals(str3));

        System.out.println(str4 == str2);
        System.out.println(str4.equals(str2));

    }
}

Definition of String String

format (two)

Iterate over the string:

public char charAt(int index): return character by index

 for (int i = 0; i < str6.length(); i++) {
    
    
            char ch = str6.charAt(i);
            System.out.println(ch);
        }

public int length(): Return the length of this string
The length of the array: 数组名.lengthlength property
The length of the string: 字符串对象.length()length() method

 String str6 = sc.next(); // 从用户输入中读取一个字符串,并赋值给str6
 int[] arr = new int[2];
 System.out.println(arr.length);
 System.out.println(str6.length());

how to traverse

A common approach is to use the enhanced for loop (also known as the foreach loop) to iterate over each character in the string. Examples are as follows:

String str = "Hello, World!";
for (char ch : str.toCharArray()) {
    
    
    System.out.println(ch);
}

This code will output every character in the string.

Another way is to loop through the string by indexing. Examples are as follows:

String str = "Hello, World!";
for (int i = 0; i < str.length(); i++) {
    
    
    char ch = str.charAt(i);
    System.out.println(ch);
}

This code will output each character in the string in turn.

These are common methods for traversing strings in Java, and you can choose the appropriate method to operate according to your specific needs.

Why in Java, when getting a length, the array is length, and the string must be length () requires multiple parentheses

在Java中,获取数组的长度使用的是length属性,而获取字符串的长度需要使用length()方法。

(1) This is because an array is a fixed-size container in Java, and its length is an attribute of the array type, which can be directly accessed through the length attribute.
(2) The string is an object, represented by the String class in Java, which has a built-in method length() to return the length of the string.

Therefore, the length of the array is obtained through the property, and the length of the string is obtained through the method, so the length() method needs to be used on the string, and a pair of parentheses need to be used because the method needs to be called.

A quick way to iterate over a string

A common approach is to use the enhanced for loop (also known as the foreach loop) to iterate over each character in the string. Examples are as follows:

toCharArray()是Java中String类的一个方法,用于将字符串转换为字符数组。
把字符串str转换成字符数组是因为在Java中,字符串是一个对象,而字符数组是字符的有序集合。
通过将字符串转换为字符数组,可以按照字符的顺序逐个遍历和访问每个字符元素。
使用字符数组可以更方便地对字符串进行操作和处理,例如搜索、替换、拆分等操作。
String str = "Hello, World!";
for (char ch : str.toCharArray()) {
    
    
    System.out.println(ch);
}

This code will output every character in the string.

Why can't each element of the string be traversed directly through string operations:

In Java, strings are immutable objects, which means that once created, the value of a string cannot be modified. This means that you cannot iterate over each element in a string directly through string operations.

When you iterate over a string using string manipulation methods (such as charAt(), substring(), etc.), you actually represent each character by returning a new String object. This will cause a new string object to be created for each operation, resulting in memory overhead and performance loss.

Converting a string to a character array can directly manipulate the elements in the character array, because the character array is mutable. You can access each character by index, or by looping through the character array to get each character element without creating a new string object. This allows for more efficient handling and manipulation of the string's contents.

Therefore, it may be more efficient and convenient to convert a string to a character array in cases where each element of the string needs to be traversed and manipulated.

Another way is to loop through the string by indexing. Examples are as follows:

String str = "Hello, World!";
for (int i = 0; i < str.length(); i++) {
    
    
    char ch = str.charAt(i);
    System.out.println(ch);
}

This code will output each character in the string in turn.

These are common methods for traversing strings in Java, and you can choose the appropriate method to operate according to your specific needs.

statistical characters

Enter a character string with the keyboard, and count the number of occurrences of uppercase letters, lowercase letters, and numbers in the string:

import java.util.Scanner;

public class CharacterCount {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("请输入一个字符串: ");
        String str = scanner.nextLine();
        
        // 统计大写字母、小写字母和数字字符的次数
        int uppercaseCount = 0;
        int lowercaseCount = 0;
        int digitCount = 0;
        
        // 遍历字符串中的每个字符
        for (char ch : str.toCharArray()) {
    
    
            if (Character.isUpperCase(ch)) {
    
    
                uppercaseCount++;
            } else if (Character.isLowerCase(ch)) {
    
    
                lowercaseCount++;
            } else if (Character.isDigit(ch)) {
    
    
                digitCount++;
            }
        }
        
        System.out.println("大写字母个数: " + uppercaseCount);
        System.out.println("小写字母个数: " + lowercaseCount);
        System.out.println("数字个数: " + digitCount);
    }
}

explain:

  • First, we create an Scannerobject to read user input.
  • Then, prompt the user to enter a string through System.out.printand , and save the string entered by the user in a variable .scanner.nextLine()str
  • We define three variables uppercaseCount, lowercaseCountand digitCountare used to count the number of uppercase letters, lowercase letters, and numeric characters, and the initial value is 0.
  • Next, we iterate through each character in the string using an enhanced for loop.
  • For each character:
    -(0) toCharArray() is a method of the String class in Java, which is used to convert a string into a character array.
    (1) Use Character.isUpperCase(ch)to judge whether it is a capital letter, if yes, uppercaseCountadd 1;
    (2) Use Character.isLowerCase(ch)to judge whether it is a lowercase letter, if yes, then lowercaseCountadd 1;
    (3) Use to Character.isDigit(ch)judge whether it is a numeric character, if it is, then digitCountadd 1 .
  • Finally, we System.out.printlnoutput the number of uppercase letters, the number of lowercase letters, and the number of numbers by printing the statistical results.

other:

forLoop through the string and use logical AND ( &&) to give the range


        // 遍历字符串中的每个字符
        for (int i = 0; i < str.length(); i++) {
    
    
            char ch = str.charAt(i);
            
            // 判断字符是否为大写字母,并增加uppercaseCount计数
            if (ch >= 'A' && ch <= 'Z') {
    
    
                uppercaseCount++;
            }
            // 判断字符是否为小写字母,并增加lowercaseCount计数
            else if (ch >= 'a' && ch <= 'z') {
    
    
                lowercaseCount++;
            }
            // 判断字符是否为数字,并增加digitCount计数
            else if (ch >= '0' && ch <= '9') {
    
    
                digitCount++;
            }
        }


}

explain:

  • We use an integer variable ias the index, the initial value is 0, and gradually increase until the length of the string is reached str.length()to continue the loop.
  • In each loop, use charAt(i)the method to get ithe character at index and save it in a variable ch.
  • Next, we use the logical AND ( &&) and the ASCII code range of the character to determine whether the character is an uppercase letter, lowercase letter or number, and perform a corresponding counting operation.

flip string

You can flip a string using StringBuilder class or char array in Java. Here are examples of both methods:

Method 1: Use the StringBuilder class

public static String reverseString(String str) {
    
    
    StringBuilder sb = new StringBuilder(str);
    sb.reverse();
    return sb.toString();
}

Example usage:

String originalString = "Hello, World!";
String reversedString = reverseString(originalString);
System.out.println(reversedString);  // 输出:!dlroW ,olleH

Method 2: Use character array [double pointer]

public static String reverseString(String str) {
    
    
    char[] charArray = str.toCharArray();
    int left = 0;
    int right = charArray.length - 1;
    
    while (left < right) {
    
    
        char temp = charArray[left];
        charArray[left] = charArray[right];
        charArray[right] = temp;
        left++;
        right--;
    }
    
    return new String(charArray);
}

Example usage:

String originalString = "Hello, World!";
String reversedString = reverseString(originalString);
System.out.println(reversedString);  // 输出:!dlroW ,olleH

Method 3: It is also feasible to use a for loop to perform string flipping.

You can do this by iterating over each character in the string and concatenating them in reverse order into a new string. Here is an example of a method using a for loop:

public static String reverseString(String str) {
    
    
    StringBuilder sb = new StringBuilder();
    
    for (int i = str.length() - 1; i >= 0; i--) {
    
    
        sb.append(str.charAt(i));
    }
    
    return sb.toString();
}

Example usage:

String originalString = "Hello, World!";
String reversedString = reverseString(originalString);
System.out.println(reversedString);  // 输出:!dlroW ,olleH

This method can also flip the string, and finally get the reversed string by traversing and splicing characters step by step.

Rotate string:

(1) Intercept with substring
(2) Turn the string into a character array first, adjust the character array data, and finally transfer the character array out of the string.

StringBuilder: A builder (container) that constructs an empty string with variable content.for concatenating strings and flipping strings

first,The String type is immutable, that is, each string concatenation operation will create a new string objectFrequent creation and destruction of string objects can cause performance problems when large numbers of strings need to be concatenated.
The StringBuilder class solves this problem. itA mutable character array is maintained internally for storing strings, and each splicing only needs to modify the content in the array without creating a new string object. In this way, frequent memory allocation and destruction can be avoided, and splicing performance can be improved.

Secondly, StringBuilder also provides some optimization methods, such as pre-allocating memory space to avoid frequent array expansion operations; by setting the initial capacity, reducing the number of array expansion times and memory copy overhead.
In general, StringBuilder provides a more efficient string concatenation method through variable character arrays and some optimization strategies, especially suitable for scenarios that require frequent concatenation of a large number of strings.

String content can be appended by calling the append() method of the StringBuilder object, so as to realize string splicing. Every time a string is appended, the character array inside StringBuilder will automatically expand to accommodate new characters. This avoids creating new string objects and improves splicing efficiency.

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString(); // 将 StringBuilder 对象转换为 String 类型的结果
System.out.println(result); // 输出:Hello World

It can be seen that by continuously calling the append() method, we can continuously append string content to the StringBuilder object, and finally convert it into a String type result by calling the toString() method. It should be noted that because StringBuilder is variable, it is not thread-safe. If it is used in a multi-threaded environment, appropriate synchronization control is required.

The source code analysis of StringBuilder is as follows:

  1. Creates a character array ( ) of length 16 by default char[] value. This array is used to store string content.

  2. When adding string content, if the length of the content to be added is less than or equal to the remaining capacity of the current array ( value.length - count), then directly copy the content to the array, and update countthe number of characters stored.

  3. If the length of the added content is greater than the remaining capacity of the current array, an expansion operation is required. Expansion takes the following steps:

    • Calculate the new capacity: original capacity * 2 + 2, ie int newCapacity = (oldCapacity << 1) + 2.
    • Check that the new capacity is large enough to accommodate the content-length to be added ( count + len). If not, the new capacity will be based on the length of the content to be added.
    • Create a new character array ( char[] newValue = new char[newCapacity]) as the expanded storage space.
    • Copy the original character data into the new array ( System.arraycopy(value, 0, newValue, 0, count)).
    • The update valuereference points to the new array, countupdated with the number of characters already stored.
  4. When the concatenation operation is performed, append()the new string content is actually appended to valuethe end of the array by consecutive calls to the series of methods, and countthe number of characters stored is updated.

Summary: StringBuilder uses a variable character array to store string content, and uses an expansion mechanism to ensure that it can accommodate strings of any length. During the splicing operation, frequent creation and destruction of string objects is avoided, thereby improving performance and saving memory space.

StringBuilder str = new StringBuilder();


System.out.println(str.capacity());//容量: 当前最多能存储多少
System.out.println(str.length());//长度: 当前实际能存储多少

The code used to detect the time;

To get the runtime of your Java code, you can use the System.currentTimeMillis() method. In the given code, you have chosen the System.currentTimeMillis() method, which is the correct way. This method returns the number of milliseconds since January 1, 1970, which can be used to calculate the execution time of the code.
In your code, you can save the return value of the System.currentTimeMillis() method in a variable, and then call the System.currentTimeMillis() method again after the code is executed, and subtract the two timestamps to get The execution time of the code.

public class new1 {
    
    
    public static void main(String[] args) {
    
    
        long startTime = System.currentTimeMillis();

        // 你的代码

        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        System.out.println("代码执行时间:" + executionTime + "毫秒");
    }
}

Construction method: new out –>StringBuilder str = new StringBuilder();

Empty parameter construction: public StringBuilder() Create a blank variable string object without any content
Construct with parameters: public StringBuilder(String str)Create a variable string object according to the content of the string

Common methods:

StringBuilder is a variable string, which provides some common methods to manipulate string content. The following are common methods of StringBuilder:

  1. append(String str): Append the specified string to the end of StringBuilder.The append() method is a method of the StringBuilder class.
  2. insert(int offset, String str): Insert a string at the specified position.
  3. delete(int start, int end): Delete characters within the specified range.
  4. replace(int start, int end, String str): Replaces the specified range of characters with the specified string.
  5. reverse(): Reverse the order of characters in StringBuilder.
  6. length(): Returns the length of the current StringBuilder.
  7. capacity(): Returns the capacity of the current StringBuilder.
  8. charAt(int index): Returns the character at the specified position.
  9. setCharAt(int index, char ch): Replace the character at the specified position with a new character.
  10. substring(int start): Returns the substring from the specified position to the end of the string.
  11. substring(int start, int end): Returns the substring within the specified range.
    These methods can help us perform operations such as insertion, deletion, replacement, and inversion when manipulating strings without creating new string objects. This improves performance and efficiency.

Compared

StringBuilder splicing: A variable character array is maintained internally for storing strings. Each splicing only needs to modify the contents of the array without creating a new string object

 StringBuilder str = new StringBuilder();

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < Math.pow(10, 5); i++) {
    
    
            str.append("abc ");

        }
        str.append(123).append(123123);//链式调用
        System.out.println(str);
        System.out.println(str.toString());
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        System.out.println("代码执行时间:" + executionTime + "毫秒");

insert image description here

Ordinary concatenation operation: Each string concatenation operation creates a new string object.

	  long startTime = System.currentTimeMillis();
        String str = "";
        for (int i = 1; i < Math.pow(10, 5); i++) {
    
    
            str += "abc ";
        }
        System.out.println(str);
        System.out.println(str.toString());
        System.currentTimeMillis();
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        System.out.println("代码执行时间:" + executionTime + "毫秒");

insert image description here

With stringbuilder in java, why do you need tostring:

In Java, the StringBuilder class is used to efficiently handle mutable strings. It provides a set of methods to perform operations such as string concatenation, insertion, and deletion without creating new String objects.

However, the StringBuilder object itself is not a string, it is a mutable sequence of characters. If you need to convert the StringBuilder object to a String object for other operations, you need to use the toString() method.

The toString() method is a method of the Object class, so all Java objects can call it. What it does is return a string representing the value of that object, typically used to convert an object to a string representation.

For a StringBuilder object, calling the toString() method will return a String object containing the contents of the StringBuilder object. In this way, it is convenient to convert between StringBuilder and String for further processing of the string or splicing with other String objects.

Therefore, although StringBuilder provides a wealth of string manipulation methods, it is still necessary to convert it into a String object by calling the toString() method in some scenarios.

The main reasons for converting StringBuilder objects to String objects are as follows:

  1. String operations: The StringBuilder class provides many methods for operations such as string concatenation, insertion, and deletion, but these methods still return StringBuilder objects. If you need to perform other string operations, such as using regular expressions, string matching functions, or other string processing methods, you usually need to convert it to a String object for further operations.

  2. API compatibility: Some APIs or libraries only accept parameters of type String, and cannot directly accept parameters of type StringBuilder. In this case, the StringBuilder object needs to be converted to a String object to interact with these APIs or libraries.

  3. Output printing: When outputting the result to the console or log file, it is usually necessary to convert the content in StringBuilder into a String object for output.

  4. Immutability: String objects are immutable, while StringBuilder objects are mutable. If you want to preserve the immutability of the string, you can convert the StringBuilder to a String object to avoid accidental modification.

In summary, the reason for converting StringBuilder to String is based on business requirements, API compatibility, output format, and immutability of strings, so as to better adapt to different scenarios and operations.

Code example:

 Scanner scanner = new Scanner(System.in);
        //键盘录入
        System.out.print("请输入字符串:");
        String inputString = scanner.nextLine();
        //翻转
        StringBuilder stringBuilder = new StringBuilder(inputString);//或者用append()方法
        stringBuilder.reverse();
        
        //tostring
        String reversedString = stringBuilder.toString();
      
        System.out.println("翻转后的字符串:" + reversedString);

一步到位 StringBuilder stringBuilder= new StringBuilder(inputString).reverse().toString();
We first created a Scanner object and passed in System.in as a parameter to read data from standard input. Then use the scanner.nextLine() method to read a complete line of string entered by the user and store it into a String variable called inputString.

Next, we created a StringBuilder object and passed inputString as a parameter of the constructor to initialize the content of StringBuilder as the input string. Then, we call the reverse() method to reverse the string.

Finally, convert the reversed StringBuilder object to a String object by calling the toString() method and store the result in a variable named reversedString. The final step is to print out the reversed string.

Execute the above code, after the prompt message is output on the console, you can enter any character string and press Enter to confirm. Then the program will reverse the string you input and display it on the console.

return:

  public static void main(String[] args) {
    
    
        char[] arr = {
    
     1, 'A', 3, 4 };
        String strs = arrtostring(arr);
        System.out.println(strs);//[, A, , ]
    }

    public static String arrtostring(char[] arr) {
    
    
        StringBuilder sss = new StringBuilder();
        sss.append('[');
        for (int i = 0; i < arr.length; i++) {
    
    
            if (i == arr.length - 1) {
    
    
                sss.append(arr[i]);
            } else {
    
    
                sss.append(arr[i]).append(", ");  //  sss.append(arr[i] + ",");
            }
        }
        sss.append(']');
        return sss.toString();
    }

If it is int[] arr = { 1, 'A', 3, 4 }
the result is [1, 65, 3, 4]

In Java, in order to avoid creating a large number of temporary string objects, we can use the StringBuilder or StringBuffer class for string concatenation.

Both StringBuilder and StringBuffer are variable character sequences, and they provide a series of methods for modifying and concatenating existing strings without creating new string objects every time. This can effectively save memory space and improve performance.

When we need to concatenate multiple strings, we can gradually append the content to the StringBuilder (or StringBuffer) object by continuously calling the append() method of StringBuilder (or StringBuffer), and finally get the final result string by calling the toString() method .

This method takes advantage of the characteristics of variable character sequences, internally only creates a StringBuilder (or StringBuffer) object, and gradually modifies and concatenates strings in this object, avoiding frequent creation of temporary string objects, thus saving memory space.

It should be noted that StringBuilder is non-thread-safe and suitable for single-threaded environments; while StringBuffer is thread-safe and suitable for multi-threaded environments. Select the appropriate class to perform string splicing operations according to actual needs.

Representation in classes and objects:

insert image description here

Stringjoiner: A specific delimiter builds a sequence of strings for concatenating strings.

StringJoiner is a class in Java that is used to build a sequence of strings with a specific delimiter. It provides a convenient way to concatenate strings while controlling the separator between them. By specifying a delimiter and optional prefix and suffix, you can add multiple strings and convert them into a single string using the specified delimiter. This is useful when you need to construct comma-separated values (CSV), SQL statements, or any other string concatenation scenarios.

StringJoineris a class in Java that is used to build a sequence of strings with a specific delimiter. It provides a convenient way to concatenate strings and control the separator between them. By specifying a delimiter and optional prefix and suffix, multiple strings can be appended and converted into a single string using the specified delimiter. This is useful when you need to build comma-separated values ​​(CSV), SQL statements, or other string concatenation scenarios.

 public static void main(String[] args) {
    
    
        int[] arr = {
    
     1, 'A', 3, 4 };
        String strs = arrToString(arr);
        System.out.println(strs); // [1, A, 3, 4]
    }

    public static String arrToString(int[] arr) {
    
    
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        for (int c : arr) {
    
    
            sj.add(String.valueOf(c));
        }
        return sj.toString();
    }

introduce

StringJoiner类是在Java 8中引入的,作为Java标准库的一部分。
它提供了一种简便的方式来连接多个字符串,并且在连接过程中可以指定分隔符、前缀和后缀等信息。

The emergence of StringJoiner is mainly to simplify the operation of string connection. Before Java 8, to concatenate multiple strings, you usually need to use StringBuilder or StringBuffer for manual splicing, which involves some tedious operations, such as appending strings, processing separators, and so on. Using the StringJoiner class can accomplish this task more intuitively, making the code more concise and clear.

Use the StringJoiner class to conveniently splice strings of lists, arrays, and other data, especially for scenarios where multiple elements need to be spliced.

For example, you can use StringJoiner to join a list of strings:

List<String> strings = Arrays.asList("apple", "banana", "orange");

StringJoiner joiner = new StringJoiner(", "); // 使用逗号和空格作为分隔符

for (String s : strings) {
    
    
    joiner.add(s);
}

String result = joiner.toString();

System.out.println(result); // 输出:apple, banana, orange

In the above example, we first created a StringJoiner object joinerand specified comma and space as delimiters. Then iterate through the list of strings, adding each string to the StringJoiner object. Finally, toString()the method is called to obtain the spliced ​​string result.

It should be noted that the emergence of the StringJoiner class is mainly to provide a convenient tool for simplifying the operation of string connection, and it is not necessary to use it. In some scenarios, you can still use methods such as StringBuilder to concatenate strings.

StringJoiner is defined as follows:

public class StringJoiner {
    
    
    // 构造函数:创建一个新的StringJoiner对象
    public StringJoiner(CharSequence delimiter)
    
    // 构造函数:创建一个新的StringJoiner对象,指定分隔符和前缀、后缀
    public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

    // 添加一个元素到StringJoiner中
    public StringJoiner add(CharSequence element)
    
    // 合并另一个StringJoiner对象到当前对象中
    public StringJoiner merge(StringJoiner other)
    
    // 获取当前StringJoiner对象中的字符串结果
    public String toString()
}

The StringJoiner class provides multiple constructors to create instances. The first constructor takes in a delimiter delimiterto specify the delimiter to use when concatenating strings. The second constructor can also pass in a prefix prefixand a suffix suffix, which are used to add extra strings before and after the final concatenation result.

By calling add()the method, an element can be added to the StringJoiner object. Methods can be called consecutively add()to add multiple elements.

Use merge()the method to merge the contents of another StringJoiner object into the current object.

Finally, the calling toString()method can obtain the string result after joining in the StringJoiner object.

Note that CharSequence is an interface that is a common parent interface to many Java string types, including String and StringBuilder.

public StringJoiner merge(StringJoiner other)

merge(StringJoiner other): Merge another StringJoiner object into the current object. This method will add the elements in another object to the end of the current object and splice according to the set delimiter. For example:

StringJoiner sj1 = new StringJoiner(",");
sj1.add("apple");
sj1.add("banana");

StringJoiner sj2 = new StringJoiner(":");
sj2.add("car");
sj2.add("bike");

sj1.merge(sj2);
System.out.println(sj1.toString()); // 输出:apple,banana,car:bike

toString(): Get the string result in the current StringJoiner object. This method returns a string of all elements in the current object concatenated according to the set delimiter. For example:

StringJoiner sj = new StringJoiner("-");
sj.add("Java");
sj.add("Python");
sj.add("C++");

String result = sj.toString();
System.out.println(result); // 输出:Java-Python-C++

public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) and public StringJoiner add(CharSequence element) together to write a code

public class Main {
    
    
    public static void main(String[] args) {
    
    
        StringJoiner stringJoiner = new StringJoiner(", ", "[", "]"); // Create a new StringJoiner object with comma and space as the delimiter, "[" as prefix, and "]" as suffix
        
        stringJoiner.add("Apple"); // Add "Apple" to the StringJoiner
        stringJoiner.add("Banana"); // Add "Banana" to the StringJoiner
        stringJoiner.add("Orange"); // Add "Orange" to the StringJoiner
        
        String result = stringJoiner.toString(); // Get the string result of the StringJoiner
        
        System.out.println(result); // Output: [Apple, Banana, Orange]
    }
}

This code creates a StringJoiner object with a comma and space (", ") as the delimiter, “[” as the prefix, and “]” as the suffix. It adds three elements (“Apple”, “Banana”, and “Orange”) to the StringJoiner using the add() method. Finally, it retrieves the string result using the toString() method and prints it to the console, which will output “[Apple, Banana, Orange]”.

Public StringJoiner(CharSequence delimiter) and public StringJoiner add(CharSequence element) cooperate to write a code

public class Main {
    
    
    public static void main(String[] args) {
    
    
        StringJoiner stringJoiner = new StringJoiner(", "); // Create a new StringJoiner object with comma and space as the delimiter
        
        stringJoiner.add("Apple"); // Add "Apple" to the StringJoiner
        stringJoiner.add("Banana"); // Add "Banana" to the StringJoiner
        stringJoiner.add("Orange"); // Add "Orange" to the StringJoiner
        
        String result = stringJoiner.toString(); // Get the string result of the StringJoiner
        
        System.out.println(result); // Output: Apple, Banana, Orange
    }
}

This code creates a StringJoiner object with a comma and space (", ") as the delimiter. It then adds three elements (“Apple”, “Banana”, and “Orange”) to the StringJoiner using the add() method. Finally, it retrieves the string result using the toString() method and prints it to the console, which will output “Apple, Banana, Orange”

string principle

The memory principle of string storage: the string constant value will be reused directly; new one

Strings in Java are immutable, i.e. once created, its value cannot be modified. The storage memory principle of Java string involves three important concepts: string constant pool, heap memory and string literal value.

  1. String constant pool (String Pool): The string constant pool is a special memory area in Java for storing string constants. When we create a string, if the value of the string already exists in the string constant pool, then the corresponding reference in the constant pool will be returned directly; if the value of the string is not in the constant pool, then the character will be String added to the constant pool, and returns the newly added reference. The existence of the string constant pool can save memory space and improve string access efficiency.

  2. Heap Memory: In addition to the string constant pool, string objects in Java can also be stored in heap memory. When we use keywords newto create a string object, the object will be stored in the heap memory and will not enter the string constant pool. The string object created by each pass newwill allocate new space in the heap memory, even if the content of the string is the same.

  3. String literals: String literals are string literals that are directly enclosed in double quotes. When we use a string literal to create a string object, Java will first look for an equal string in the string constant pool. If it exists, return the corresponding reference in the constant pool; if not, create a new string in the constant pool and return the reference.

In general, the principle of string storage memory in Java can be simply summarized as: share and reuse strings through the string constant pool, improve performance and save memory space; while string newobjects created using keywords will Allocate separate space in heap memory.

== sign and equals() method comparison

In Java, both the "=" operator and the equals() method can be used to compare objects for equality, but they have different behaviors.

  1. "" operator: It is a comparison reference operator. When using ""When comparing two objects, it checks whether the references of the two objects point to the same object in memory. If the two references point to the same object, it returns true; otherwise, it returns false. For example:

    String str1 = "Hello";
    String str2 = "Hello";
    System.out.println(str1 == str2);  // true
    

    基本数据类型比较数据值
    引用数据类型比较地址值
    In the above example, although str1 and str2 are two different references, they point to the same string object in the string constant pool.

  2. equals() method: It is a method defined in the Object class, which is overridden in many concrete classes to implement custom equality comparison logic. The equals() method is used to compare the contents of two objects for equality. By default, the equals() method behaves the same as the "==" operator, that is, compares whether the references of two objects are the same. However, many classes (such as String, Integer, etc.) have overridden the equals() method to use it to compare content. For example:

    String str1 = new String("Hello");
    String str2 = new String("Hello");
    System.out.println(str1.equals(str2));  // true
    

    In the above example, the equals() method of the String class is called to compare whether the contents of two string objects are equal.

Summarize:

  1. The "==" operator compares references for equality.
  2. The equals() method may have different implementations in different classes, and is used to compare whether the contents of objects are equal. For the String class, the equals() method compares the contents of the strings.
    Therefore, when comparing two strings, it is generally recommended to use the equals() method to compare their contents rather than the "==" operator.

The underlying principle of string splicing:

**如果没有变量参与,都是字符串直接相加,编译之后就是拼接之后的结果,
	会复用串池中的字符串如果有变量参与,每一行拼接的代码,都会在内存中创建新的字符串,浪费内存。
在Java中,字符串拼接可以使用"+"运算符或concat()方法来实现。
	字符串拼接的底层原理涉及到字符串对象和字符数组的处理。**
所有要拼接的内容都会往StringBuilder中放,不会创建很多无用的空间,节约内存
  1. Use the "+" operator: When we use the "+" operator for string splicing, a new StringBuilder object is actually created, and the strings to be spliced ​​are added to the StringBuilder one by one. Finally, StringBuilder will call the toString() method to generate a new String object, which contains the concatenated string content. This approach is suitable for a small number of simple string concatenation operations.
    Multiple string variables are concatenated, do not directly +. Under the hood multiple objects are created, wasting time and performance.
    For example:

    String str = "Hello" + " " + "World!";
    

    The code above is equivalent to:

    StringBuilder sb = new StringBuilder();
    sb.append("Hello").append(" ").append("World!");
    String str = sb.toString();
    
  2. Use the concat() method: The String class provides the concat() method, which is used to concatenate the current string with the specified string and return a new String object. The internal implementation is similar to the "+" operator, which creates a new StringBuilder object and performs string concatenation. For example:

    String str1 = "Hello".concat(" ").concat("World!");
    

Whether using the "+" operator or the concat() method, the essence of string splicing is to operate through StringBuilder or StringBuffer. Each string is added to the variable character array one by one, and then a new String object is generated and returned. This method avoids frequent creation and destruction of string objects and improves efficiency.
Please note that since strings in Java are immutable, each string concatenation operation will create a new string object and return it. If you need to splice a large number of strings frequently or in a loop, it is recommended to use StringBuilder or StringBuffer to optimize performance.

When the string to be concatenated has been determined at compile time and no variables are involved, the Java compiler will directly concatenate consecutive string literals to avoid using the StringBuilder or StringBuffer classes.

This is due to the Java compiler's optimization mechanism for strings, called the string constant pool. During compilation, if consecutive string literals are found, the compiler will combine them into one string and store it in the string constant pool. Therefore, the string concatenation operation in this case will be optimized to a constant at compile time.

For example, the following code snippet:

String str = "Hello" + ", " + "World!";

At compile time, it will be optimized to:

String str = "Hello, World!";

This reduces string concatenation operations at runtime and improves performance.

Please note that the == optimization only applies to concatenation of string literals, not string concatenation involving variables. == When variables are involved, it is still recommended to use StringBuilder or StringBuffer for string splicing to avoid frequent creation of temporary objects and improve performance.

For string concatenation in Java, when all the parts involved in concatenation are string literals, the compiler will perform string optimization. This optimization mechanism is called "string constant pool", and its function is to reduce memory usage by sharing the same string in memory.

In the compilation stage, if the expression contains only string literals, the compiler will concatenate them into a string, and embed the final result directly into the generated bytecode as a string constant. In this way, there is no need to perform string splicing operations at runtime, because the splicing has already been done at compile time.

It should be noted that when string concatenation involves variables or expressions, the compiler cannot determine the final string result at compile time, so the string optimization mechanism will not be triggered in this case. In this case, the string concatenation operation will be performed at runtime.

To sum up, only when all the parts involved in splicing are string literals, the Java compiler will trigger the string optimization mechanism to concatenate them into a string constant at compile time.

Before Java 8, the mechanism for string concatenation was different compared to now.

Before Java 8, when using the plus sign "+" for string concatenation, each concatenation will create a new string object. This is because strings are immutable in Java, and each concatenation needs to create a new string object to save the result. This will lead to frequent memory allocation and recovery, which will have a certain impact on performance.

Among the new features introduced by Java 8, the StringJoiner class and the String.join() method are introduced to perform string concatenation operations more efficiently. These methods internally use the StringBuilder class to handle string splicing, which avoids frequent creation and destruction of string objects and improves performance.

In addition, after Java 9, a more convenient string splicing method was introduced, using placeholders ("%s") and the static method String.format() for string formatting and splicing.

To sum up, the string splicing mechanism before Java 8 and the new features introduced after Java 8 have certain differences in handling string splicing. The introduction of new features can improve the performance of string concatenation and the readability of code.

When splicing strings, if there are variables:

Before JDK8, the string splicing operation will indeed automatically create an StringBuilderobject through the bottom layer of the system, and call its append()method to complete the splicing. After splicing is complete, call toString()the method to StringBuilderconvert the object into Stringa type. In toString()the underlying implementation of the method, keywords will be used to newcreate a new string object to store the final splicing result.

In the JDK8 version and later, the JVM will directly allocate a character array to store the content to be spliced ​​according to the estimated total size after splicing, and perform the splicing operation. This avoids frequent creation and destruction of temporary objects during splicing StringBuilder. A new string object is only generated when doing an explicit string-to- Stringtype conversion or calling a specific Stringclass method (for example ).toUpperCase()

The JDK8 version introduces Compact Stringsthe feature based on byte array, which uses byte array to store string data, saves memory space and improves performance. This optimization method also makes string concatenation more efficient.


  1. Due to the characteristics of string literals, string objects with the same content will be shared and stored in the string constant pool, which can improve memory utilization and efficiency. The string object created by the new keyword will not be saved in the string constant pool. ↩︎

Guess you like

Origin blog.csdn.net/m0_74154295/article/details/131483696