In Java, the difference between using concat method for String concatenation and direct concatenation with "+" connector

In the String class, string splicing can either use the concat method or directly connect with the connector. What are the similarities and differences between the two? The following editor will take you to look at it through the code.

Use of the concat method: public String concat(String str): concatenate the current string and the parameter string into a new string of the return value.

In other words, concat can splice the string in the parameter list with the current string, and the return value is a new string.

Usage of the "+" connector: It's very simple, just use the connection directly.

Let's take a look at their similarities and differences through the code.

public class Demo10String {
    public static void main(String[] args) {
        //拼接字符串相同点
        String str1="Hello";
        String str2="World";
        String str3=str1.concat(str2);
        String str4=str1+str2;
        System.out.println(str3);   //输出:HelloWorld
        System.out.println(str4);   //输出:HelloWorld
        //不同点
        String str="Hello" + 5;     //输出:Hello5
        System.out.println(str);
}

We can see from the above code:

Similarity 1: Both the concat method and the direct splicing with the "+" connector can splice two strings.

Similarity 2: Both splicing methods will re-form a new string. This is because the content of the string will never change, so the splicing will definitely form a new string.

Difference: concat can only concatenate two strings; but the "+" connector can concatenate strings and non-string types together (note: as long as one of the two is a string type, use the "+" connector Will be spliced ​​into a new string).

In addition, when we generate a class file and then decompile it, we can find through the concat source code that StringBuilder creates more objects with the linker, but concat does not. The String class it uses Internal implementation.

Summary: When concatenating two strings, we should give priority to using the concat() function.

           When it is necessary to connect strings and other non-string variables, cancat cannot meet the demand, we have to give priority to using the "+" connection operator.

 

Guess you like

Origin blog.csdn.net/wtt15100/article/details/108014448