Java basic grammar (9)-String class

Article Directory

Java basic grammar (9)-String class


Outline of this content introduction


Insert picture description here



String is a very commonly used type in our future work. It is very simple and convenient to use, we must use it skillfully.


So is there a string type in C language? The answer is "no"! !


char *p = "hello";


So is the type of p a string type? No, p is a pointer! !


In Java, there is a string type- String


One, definition method


There are many ways to create a string. Common ways to construct a String are as follows:

Method 1: Direct assignment method
String str1 = "hello";
Method 2: new String()
String str2 = new String("hello");
Method 3: Create a character array ch, new String (ch)
char chs[] = {'h','e','l','l','l','o'};
String str3 = new String(chs);


Two, memory


Before that, we must first introduce a conceptual string constant pool

Sting constant pool characteristics of string constant pool


1. Starting from JDK.7, the string constant pool was moved to the heap
2. There is no duplication of data in the pool


Let us pass a series of exercises to familiarize ourselves with the storage of string constant pool and string type data in memory.

  public static void main(String[] args) {
       String str1 = "hello";
       String str2 = new String("hello");
        System.out.println(str1 == str2);

        String str3 = "hello";
        System.out.println(str1 == str3);
    }


Let’s look at such a code, str represents the reference\address, please judge what is the two prints?


Let's see the result


Insert picture description here


This result shows that the addresses stored in str1 and str2 are different, and the addresses stored in str1 and str3 are the same.


Okay, why is this the result? Let's take a look at the memory of these string type variables.

Insert picture description here
If "hello" is stored in the constant pool, it will occupy memory. If the address of this space is 111, then the address stored in str1 is 111.
str2 new a String object, then memory must be opened up on the heap, assuming the memory address is 888, in this String object, there is a value[] that holds the string passed in by orginal, this val == "hello", because in There is already "hello" in the string constant pool, so val directly points to "hello" in the constant pool. But str2 still points to the space of 888 in the heap.
Insert picture description here


Insert picture description here

So str1 is not equal to str2.


After that, str3 is also equal to "hello", and he is also going to put hello in the constant pool. At this time, there is already "hello" in the constant pool. Then, when str3 stores the address of "hello", it points to the constant pool. The address of the original hello in the middle.


So str1 is equal to str3


Look at another set of exercises

    public static void main(String[] args) {

        String str1 = "hello";
        String str2 = "hel"+"lo";
        System.out.println(str1==str2);

        String str3 = new String("hel")+"lo";
        System.out.println(str1==str3);

    }

Please judge the result of two prints...

The results are as follows:

Insert picture description here


Let's analyze the memory storage of the str variable in this group of codes

Insert picture description here
str1 points to "hello" in the string constant pool
str2 is a combination of "hel" and "lo". The constant is determined when compiling, so it has been processed as "hello" when compiling, so it also points to "hello" in the constant pool.


So str1 is equal to str2


str3 first creates a new String ("hel") object and opens up a space in the heap. The "hel" in this object is stored in the constant pool at the same time, and then a space is opened in the constant pool to store "lo". The "+" between the two parts combines the String object with the "lo" in the constant pool to open up a new space in the heap again, the val == "hello" in this memory, and str3 points to the merge The object after that has the address 999.

So str1 is not equal to str3.


Look at another set of exercises

 public static void func(String str,char[] array){
        str = "abcdef";
        array[0] = 'g';
    }

    public static void main(String[] args) {
        String str1 = "hello";
        char[] val = {'a'};
        System.out.println(str1);
        System.out.println(Arrays.toString(val));
        func(str1,val);
        System.out.println("=================");
        System.out.println(str1);
        System.out.println(Arrays.toString(val));
    }


Please take a look, we take String str as a parameter, change the content of str, and pass in the array val to change the array elements. What is the printed result?


Insert picture description here



We see that the content of String str has not changed, but the elements of the array val have changed.

We analyze from the perspective of memory.

Insert picture description here
str1 points to "hello" in the string constant area, the address is 888
val is used as an array reference, pointing to the array space opened up in the heap, the address is 777
As a formal parameter of the function, str receives the value of the actual parameter of str1, which is 888. At this time, str points to "hello" in the constant area, but inside the method, str = "abcde", which opens up a block in the string constant area The memory of "abcde", the address is 000, and the address stored in str is 000.
As a function parameter, array receives the value of the actual parameter of val, which is 777. At this time, array points to the array space opened up in the heap. At this time, the content of the array elements is changed through array. The final change is also the actual parameter of val. content.


Three, string comparison is equal


If there are two int type variables, you can use == to complete the judgment of their equality.

str1 = "world";
System.out.println(str2);
// 执行结果
//Hello
int x = 10 ;
int y = 10 ;
System.out.println(x == y); 
// 执行结果
//true

What if we use == on String objects now?


Code 1
String str1 = "Hello";
String str2 = "Hello"; 
System.out.println(str1 == str2); 
// 执行结果
//true 

It seems that there is no problem, and then try another code, and found that the situation is not very good.


Code 2
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2);
// 执行结果
//false


In the above exercises, we used str1 == str2 to compare the references/addresses of two strings. To compare the contents of the strings, we need to use the equals method.


 public static void main(String[] args) {
        String str1 = "hello";
        String str2 = new String("hello");
        
        System.out.println(str1==str2);          //比较的是引用
        System.out.println(str1.equals(str2));   //比较 str1 和 str2 字符串的内容
        
        String str3 = "hello";
        System.out.println(str1.equals(str3));   //比较 str1 和 str3 字符串的内容
    }

The final print result


Insert picture description here


The printed result matches the comparison of the contents of the string.

Commonly used comparison methods:

Let’s look at another situation,

  public static void main(String[] args) {
        String str1 = null;
        String str2 = "hello";
        System.out.println(str1.equals(str2));
    }

When running the program at this time, the following situations will occur:

Insert picture description here


Null pointer exception, because null. Any method will cause an exception.

So we must ensure that str1 cannot be null.

So if we change it,

public static void main(String[] args) {
        String str1 = null;
        String str2 = "hello";
        System.out.println(str2.equals(str1));
    }


So we know equals(), the brackets can be null, but it must not be null before the dot.

public static void main(String[] args) {
        String str1 = "hello";

        System.out.println(str1.equals("hello"));  // 方式1
        System.out.println("hello".equals(str1));  // 方式2
    }


When we write code and encounter the above situation, we should try to choose method 2, so as to ensure that equals must not be null before, in case an exception occurs.


Four, string constant pool


In the above example, there are two instantiation operations of the String class, direct assignment and new a new String.


(1) Direct assignment


System.out.println("Hello".equals(str));  // 执行结果 false
String str1 = "hello" ;
String str2 = "hello" ; 
String str3 = "hello" ; 
System.out.println(str1 == str2); // true
System.out.println(str1 == str3); // true
System.out.println(str2 == str3); // true


The design of the String class uses a shared design pattern

In fact, an object pool (string constant pool) is automatically maintained at the bottom of the JVM

If the direct assignment mode is now used to instantiate an object of the String class, then the instantiated object (string content) will be automatically saved in this object pool.

If you continue to use the direct assignment mode to declare the String class object next time, if there is specified content in the object pool at this time, it will be directly referenced

If not, open up a new string object and save it in the object pool for next use


Understanding "pool" (pool)
"Pool" is a common and important way to improve efficiency in programming. We will encounter a variety of "memory pools", "thread pools", "database connection pools" in our future learning... However, pools are like this The concept is not unique to computers, but comes from life.
Take a chestnut: There is a goddess in real life, called "green tea", while talking with Gao Fushuai about the object, he may also be ambiguous with other dicks. At this time This dick is called a "spare tire." So why have a spare tire? Because once you break up with Gao Fushuai, you can immediately find a spare tire to connect the disc, which is more efficient. If this goddess is engaged with many dicks at the same time Ambiguous, then these spare tires are called spare tire pools.


(2) Adopt the construction method


It is standard practice for class objects to be instantiated using constructors. Analyze the following procedures:


String str = new String("hello");
Insert picture description here


This approach has two disadvantages:


1. If you use the String construction method, two heap memory spaces will be opened up, and one of the heap memory spaces will become garbage space (the string constant "hello" is also an anonymous object, and it is no longer used after it is used once, and it becomes garbage Space, will be automatically reclaimed by JVM).
2. String sharing problem. The same string may be stored multiple times, which is a waste of space.


(3) The use of intern

String str1 = "hello";
String str2 = new String("hello").intren();


From the above definition of the string by the construction method, we will waste memory space, and here is a method called intern(), which is manually pooled.


What does this mean?


This is to first look at whether the string passed into the constructor exists in the string constant pool, and if so, pass the reference in the constant pool to the current reference type variable.

Insert picture description here

In summary, we generally use direct assignment to create String objects.

Insert picture description here

Let's look at such a set of codes again, to draw his memory structure

Insert picture description here
In the code of the first step, new two strings "1" are created, two objects are created in the heap, pointing to "1" in the constant pool, spliced ​​together, s3.interb(), s3 are manually pooled , "11" is not in the pool, so the reference 555 of "11" in the heap is passed into the constant pool. s4 points to "11" in the pool, and at this time there is already a reference to "11" in the pool, so s4 points to the reference to s3 in the pool.

So the result is true.

Insert picture description here

So, we resolved a question

In the constant pool, you can put string literal constants or quotes. When to put a reference, it is similar to the situation above, the object pointed to by s3.intern(), s3 does not exist in the string constant pool, then when entering the pool, put the s3 in the heap Reference put in.


Five, understand that strings are immutable


A string is an immutable object. Its content cannot be changed. What does this mean?

  public static void main(String[] args) {
        String str = "hello" ;
        str = str + " world" ;
        str += "!!!" ;
        System.out.println(str);
    }


For this kind of code, at first glance we think we successfully spliced ​​str with other strings each time, but this is not possible. The original str pointed to "hello", but after splicing with "world", it will Generate a new object "helll world" and splice a "!!!" again, then a new object "hello world!!!" will be generated, and multiple objects will be generated in memory.
Insert picture description here

The last thing we need is "hello world!!!", but 5 blocks of memory space have been opened up.

If spliced ​​in a loop, more memory space will be opened up! !

So such code is extremely undesirable! ! !

So how to splice it will be introduced in StringBuff and StringBuilder later.


Six, characters, bytes, strings


(1) Characters and strings


The string contains a character array, String can be converted to char[]

Insert picture description here
1. Character array to string
Insert picture description here
    public static void main(String[] args) {
        char[] val = {'h','e','l','l','o'};
        String str = new String(val);
        System.out.println(val);
    }

At this time, our str result is "hello", and he can also give two more parameters.


2. Convert the contents of part of the character array to a string
Insert picture description here


offset--offset
count-- to convert several

 public static void main(String[] args) {
        char[] val = {'h','e','l','l','o'};
        String str = new String(val,1,2);
        System.out.println(str);
    }

At this point, we offset the val by 1, and the two array elements after conversion are strings

The printed result should be el

The results of the operation are as follows:

Insert picture description here


3. Convert the corresponding index in the string to a character
Insert picture description here
 public static void main(String[] args) {
        String str = "hello";
        char ch = str.charAt(1);
        System.out.println(ch);
    }

The index starts from 0, we enter 1, so what is converted is e in the string

The results of the operation are as follows:

Insert picture description here


4. Convert a string to a character array
Insert picture description here
 public static void main(String[] args) {
        String str = "hello";
        char[] val = str.toCharArray();
        System.out.println(Arrays.toString(val));
    }

We use a character array to receive the characters after str is converted.

The results of the operation are as follows:


Insert picture description here



Well, after understanding these methods of characters and strings, we will continue to be familiar with them through a few exercises.


Exercise one

Given a character string, judge whether it is all composed of numbers.
Idea: Turn the string into a character array and then judge whether each character is between "0"~"'9'", and if it is, it is a number.
  public static boolean func1(String str){
        for (int i = 0; i <str.length() ; i++) {
            if(str.charAt(i)>'9' || str.charAt(i)<'0'){
                return false;
            }
        }
        return true;
    }


(2) Bytes and strings


Byte is often used in data transmission and encoding conversion processing, String can also be easily converted to byte[]


Common methods:

Insert picture description here
1. Convert byte array to string
Insert picture description here
  public static void main(String[] args) {
        byte[] bytes = {97,98,99,100};
        String str = new String(bytes);
        System.out.println(str);
    }

Operation result:

Insert picture description here


The content in the string is the corresponding character in the byte array and the Ascii code table.

2. Part of the content of the byte array is converted to a string
Insert picture description here
  public static void main(String[] args) {
        byte[] bytes = {97,98,99,100};
        String str = new String(bytes,2,1);
        System.out.println(str);
    }

operation result:

Insert picture description here


3. Convert string to byte array
Insert picture description here
   public static void main(String[] args) {
        String str = "abcd";
        byte[] bytes = str.getBytes();
        System.out.println(Arrays.toString(bytes));
    }

operation result:

Insert picture description here


(3) Summary


So when to use byte[] and when to use char[]?


byte[] is to process String in a byte-by-byte manner, which is suitable for use in scenarios such as network transmission and data storage. It is more suitable for operating on binary data.
char[] Yes, String is processed in a character-by-character manner, which is more suitable for operation on text data, especially when it contains Chinese.


Seven, common operations of strings


(1) String comparison


The equals() method provided by the String class has been used above, and the method itself can perform case-sensitive equality judgments. In addition to this method, the String class also provides the following comparison operations.
Insert picture description here
1. Case sensitive comparison
Insert picture description here
   public static void main(String[] args) {
        String str1 = "abcd";
        String str2 = "Abcd";
        System.out.println(str1.equals(str2));
    }

Operation result:

Insert picture description here


Our commonly used equals method is case-sensitive, so we should pay attention to this point.

2. Case-insensitive comparison
Insert picture description here
    public static void main(String[] args) {
        String str1 = "abcd";
        String str2 = "Abcd";
        System.out.println(str1.equalsIgnoreCase(str2));
    }

operation result:

Insert picture description here

This case-insensitive comparison is still very common. For example, it is not case-sensitive when applied to verification codes.


3. Compare the size relationship between two strings
Insert picture description here
public static void main(String[] args) {
        String str1 = "abcd";
        String str2 = "Abcd";
        System.out.println(str1.compareTo(str2));
    }

Run-time results

Insert picture description here


Insert picture description here


Having mastered the method of comparing strings for equality, let’s do a practice problem

Compare strings for equality
Insert picture description here


Problem solution ideas:


The contents of the word1 string array are appended to str1, and the contents of the word2 string array are appended to str2. Finally, equals compares the contents of the str1 and str2 strings, and returns true for equality and false for unequal.
Note: parameters and other issues should be considered comprehensively
Insert picture description here
Insert picture description here


(2) String search


From a complete string, you can determine whether the specified content exists. The search method has the following definitions:

Insert picture description here
Determine whether there is a substring in a string
Insert picture description here


We can first look at the source code of the contains method

Insert picture description here


Use of contains method

 public static void main(String[] args) {
       String str = "bcdabc";
       boolean flg = str.contains("abc");
        System.out.println(flg);
    }

operation result

Insert picture description here

So it can be judged that there is a substring of "abc" in the string "badabc".


Find the subscript of the substring
Insert picture description here


Let's first look at the source code of a parameter index method

Insert picture description here



Use of index method with one parameter


    public static void main(String[] args) {
        String str = "ababcabcdabcde";
        int index1 = str.indexOf("abc");
        int index2 = str.indexOf("hello");
        System.out.println(index1);
        System.out.println("============");
        System.out.println(index2);
    }

operation result:

Insert picture description here
Use of the index method with two parameters
Insert picture description here


Below we have seen another index method, which shows that by default, index is searched from 0 subscript. If you give him another subscript parameter, then the string search will be performed from the specified subscript position.


use:

 public static void main(String[] args) {
        String str = "abcabcdabcdef";
        int index1 = str.indexOf("abc");
        int index2 = str.indexOf("abc",6);
        System.out.println(index1);
        System.out.println("=================");
        System.out.println(index2);
    }

operation result:

Insert picture description here
Find the position of the substring from back to front
Insert picture description here


lastIndexOf is to find the position of the substring from back to front

Use of the lastIndexOf method

 public static void main(String[] args) {
        String str = "abcabcdabcdef";
        int index = str.lastIndexOf("abc");
        System.out.println(index);
    }

operation result:

Insert picture description here


At the same time, lastIndexOf also has a two-parameter method, which starts from the specified index and searches from back to front.


Insert picture description here


There are also two parameter methods to determine whether it starts with a parameter string . From the specified position, it can be judged whether it starts with the specified string.

Insert picture description here


Determine whether the end of the specified string
Insert picture description here


(3) String replacement

Insert picture description here
(1) Replace all specified content
Insert picture description here

Use of replaceAll

 public static void main(String[] args) {
        String str = "abcabcacbabc";
        System.out.println(str);
        System.out.println("=================");
        String ret = str.replaceAll("ab","AB");
        System.out.println(ret);
    }

operation result:

Insert picture description here


Successfully replace all "ab" with "AB".


(2) Replace the first content to be replaced.
Insert picture description here

Use of replaceFirst

 public static void main(String[] args) {
        String str = "abcabcacbabc";
        System.out.println(str);
        System.out.println("=================");
        String ret = str.replaceFirst("ab","AB");
        System.out.println(ret);
    }

operation result:

Insert picture description here



Note the description:

Since the string is an immutable object, the replacement does not modify the current string, but generates a new string.


(4) String split


A complete string can be divided into several substrings according to the specified delimiter.

Insert picture description here
1. Split all the strings
Insert picture description here


The received type is a string array type. When passing parameters, pass a symbol that we want to divide.


Use of split

  public static void main(String[] args) {
        String str = "rain7 is cool";
        String[] strs = str.split(" ");
        for (String s:strs) {
            System.out.println(s);
        }
    }

When we use the split method, we use spaces as the separator to split our str string


Let's look at the effect of split

Insert picture description here
2. Split method with two parameters
Insert picture description here


Take the above string as an example

   public static void main(String[] args) {
        String str = "rain7 is cool";
        String[] strs = str.split(" ",2);
        for (String s:strs) {
            System.out.println(s);
        }
    }

operation result:

Insert picture description here

In addition to the string as a parameter, we also set limit to 2, then the length of the split array is 2, so the running result is as shown above.


Difficulty :

Splitting is a particularly common operation. It must be mastered. In addition, some special characters may not be properly split as a separator, and escape characters need to be added


Example 1

Split IP address

For example, we want to divide the IP address, 192.168.1.1, separated by ".".

When we run, we will find that the print is empty. Why is this?

Some symbols are special, and escape characters must be used

“ \. ”才能表示一个真正的 “.” 

同时"\"也需要进行转义,那么就又要再加一个斜杠。

“\\.”这时字符串才只能被 “ . ”分割。
public static void main(String[] args) {
        String str = "192.168.1.1";
        String[] strs = str.split("\\.");
        for (String s:strs) {
            System.out.println(s);
        }
    }


operation result

Insert picture description here
1. 字符"|","*","+"都得加上转义字符,前面加上"\\".
2. 而如果是"\",那么就得写成"\\".
3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符.


Use of hyphen "|"

 public static void main(String[] args) {
        String str = "[email protected]";
        String[] ret = str.split("@|\\.");
        for (String s:ret) {
            System.out.println(s);
        }
    }

operation result:

Insert picture description here


Let's take a practice question:

Insert picture description here

Code solution:

 public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
            String ret ="";
            String str = scanner.nextLine();
            String[] strs = str.split(" ");
            for (String s:strs) {
                ret += s;
            }

            System.out.println(ret);
        }
    }

operation result:

Insert picture description here

note:

1. Pay attention to multiple sets of input
. 2. It is not recommended to splice strings in a for loop. After the StringBuilder StringBuffer mentioned later, you can know how to splice.

(5) String interception

Cut out part of the content from a complete string. The available methods are as follows:

Insert picture description here
1. Intercept from the specified subscript to the end of the string
Insert picture description here

Use of method

 public static void main(String[] args) {
        String str = "ilikeBeijing";
        String ret = str.substring(4);
        System.out.println(ret);
    }

operation result:

Insert picture description here
2. The subString method with two parameters, intercept the string content within the specified subscript range
Insert picture description here

Use of method

 public static void main(String[] args) {
        String str = "HelloWorld";
        String ret = str.substring(4,9);
        System.out.println(ret);
    }

operation result

Insert picture description here


note:

1. The specified subscript range is the interval of left closed and right open
2. The intercepted string is a new object

(6) Other operation methods

There are many other methods for string manipulation, here we only briefly introduce them.

Insert picture description here

(7) String manipulation exercises


1. Invert a string


Subject requirements

Invert the string as a whole


Code solution:

   public static String reverse(String s){
        if(s==null){
            return null;
        }

        int begun = 0;
        int end = s.length()-1;
        char[] chars = s.toCharArray();
        while(begun<end){
            char tmp = chars[begun] ;
            chars [begun] = chars [end];
            chars[end] = tmp;
            begun++;
            end--;
        }
        return new String(chars);
    }


    public static void main(String[] args) {
        String str = "Hello World!";
        String ret = reverse(str);
        System.out.println(ret);
    }


operation result:

Insert picture description here


Successfully invert the string


2. Flip the string

Insert picture description here


Let's first interpret the topic. We need to implement a method to pass a string and an integer size to this method. Flip the left half of size to the right half. as the picture shows:


Insert picture description here


Idea realization:

1. First, invert the left half of size separately.
2. Reverse the right half of the size separately.
3. The entire character string is reversed.
Insert picture description here



Code display:

 public static String reverse(String s,int begun,int end){
        if(s==null){
            return null;
        }

        char[] chars = s.toCharArray();
        while(begun<end){
            char tmp = chars[begun] ;
            chars [begun] = chars [end];
            chars[end] = tmp;
            begun++;
            end--;
        }
        return new String(chars);
    }

    public static String reversSentence(String str,int k){
        str = reverse(str,0,k-1);
        str = reverse(str,k,str.length()-1);
        str = reverse(str,0,str.length()-1);

        return str;
    }

    public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       String str = scanner.next();
       int n = scanner.nextInt();
       String ret = reversSentence(str,n);
        System.out.println(ret);
    }

operation result:

Insert picture description here

Eight, StringBuffer and StringBuilder


StringBuffer and StringBuilder are a new type of string.

通常来讲String的操作比较简单,但是由于String的不可更改特性,为了方便字符串的修改,提供 StringBuffer 和 StringBuilder 类。
StringBuffer 和 StringBuilder 在功能上大部分是相同的,在这里我们着重介绍 StringBuffer.


(1)append 方法


在String中使用"+"来进行字符串连接,但是这个操作在StringBuffer类中需要更改为append()方法。


String和StringBuffer最大的区别在于:String的内容无法修改,而StringBuffer的内容可以修改。频繁修改字符串的情况考虑使用 StingBuffer。


 public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        sb.append("a");
        sb.append("b");
        sb.append("c");
        System.out.println(sb);
    }

运行结果:

Insert picture description here


我们来看一下 StringBuffer 的 append 方法的源码

Insert picture description here


最后返回的是 this,在字符串本身拼接字符串。同时StringBuffer 有自己重写的 toString 方法,可以直接进行打印。

我们来看一下 以下的代码:

  public static void main(String[] args) {
       String str1 = "abc";
       String str2 = "def";
       String str3 = str1+str2;
       System.out.println(str3);

    }

我们对以上代码进行编译一下:

Insert picture description here


在编译的过程中,我们发现StringBuilder.append 方法的出现;

我们将这个过程用 StringBuilder 写一下:

   public static void main(String[] args) {
        String str1 ="abc";
        String str2 = "def";
        StringBuilder sb = new StringBuilder();
        sb.append(str1);
        sb.append(str2);
        String str3 = sb.toString();
        System.out.println(str3);
    }

说明:

String 的“+” 拼接,会被底层优化为一个 StringBuilder ,拼接的时候会用到 append 方法


(2)注意


注意: String和StringBuffer类不能直接转换。如果要想互相转换,可以采用如下原则:
String变为StringBuffer:利用StringBuffer的构造方法或append()方法
StringBuffer变为String:调用toString()方法。
除了append()方法外,StringBuffer也有一些String类没有的方法:


字符串反转:

public synchronized StringBuffer reverse();

(3)区别


The difference between String and StringBuilder and StringBuffer

When String is spliced, the bottom layer will be optimized to StringBuilder
The splicing of Strings will produce temporary objects, but the latter two only return references to the current object each time.
The content of String cannot be modified, and the content of StringBuffer and StringBuilder can be modified.


The difference between StringBuilder and StringBuffer

Let's take a look at the append methods of these two classes

Insert picture description here


Therefore, the difference between StringBuffer and StringBuilder is mainly reflected in thread safety.


1. Most functions of StringBuffer and StringBuilder are similar
2. StringBuffer uses synchronization processing, which is a thread-safe operation; while StringBuilder does not use synchronization processing, which is a thread-unsafe operation


String manipulation is a very common operation in our future work. It is very simple and convenient to use, we must use it skillfully.


Well, today’s knowledge will be shared here. I hope you will practice more and master it. Thank you for your appreciation and attention! !


Thank you for your appreciation!



Finish!