String Concatenation in Java – Java中的字符串连接

最后修改: 2022年 9月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

String concatenation in Java is one of the most common operations. In this tutorial, we’ll walk through some approaches to string concatenation. But, we’ll focus on describing how to use concat() and the “+” operator approaches. Finally, we’ll discuss how to select the correct one depending on what we need to do.

Java中的字符串连接是最常见的操作之一。在本教程中,我们将了解一些字符串连接的方法。但是,我们将重点描述如何使用concat()和”+“操作符的方法。最后,我们将讨论如何根据我们需要做的事情来选择正确的方法。

2. Approaches to Concatenation

2.串联的方法

In general, there are different approaches to concatenating two or more strings in Java. Furthermore, we’ll look at some examples with a description of each one.

一般来说,在Java中,有不同的方法来连接两个或多个字符串。此外,我们将看一些例子,并对每个例子进行说明。

2.1. Using the “+” Operator

2.1.使用”+“操作符

One of the most common concatenation approaches in Java is using the “+” operator.

Java中最常见的连接方法之一是使用”+“操作符

The “+” operator provides more flexibility for string concatenation over other approaches. First, it doesn’t throw any exceptions for null values. Second, it converts null into its string representation. Besides, we can use it for concatenating more than two strings.

与其他方法相比,”+“操作符为字符串连接提供了更多的灵活性。首先,它不会对空值抛出任何异常。其次,它将null转换为其字符串表示。此外,我们可以用它来连接两个以上的字符串。

Let’s see a code example:

让我们看一个代码例子。

@Test
void whenUsingPlusOperatorANull_thenAssertEquals() {
    String stringOne = "Hello ";
    String stringTwo = null;
    assertEquals("Hello null", stringOne + stringTwo);
}

The compiler internally transforms the”+” operator to a StringBuilder(or StringBuffer) class and its append() method.

编译器在内部将”+“操作符转换为StringBuilder(或StringBuffer)类及其append()方法。

Since the +” operator silently converts the argument to a String (using the toString() method for objects), we avoid the NullPointerException. However, we need to consider if our final string result works for us with the “null” in the string body.

由于+“操作符默默地将参数转换为String(对对象使用toString()方法),我们避免了NullPointerException。然而,我们需要考虑我们最终的字符串结果在字符串主体中的 “null “是否对我们有效。

2.2. Using the concat() Method

2.2.使用concat()方法

The concat() method in the String class appends a specified string at the end of the current string and returns the new combined string. Given that the String class is immutable, the original String isn’t changed.

String类中的concat()方法在当前字符串的末尾追加了一个指定的字符串,并返回新的组合字符串。鉴于String类是不可变的,原始的String并没有改变。

Let’s test this behavior:

让我们测试一下这种行为。

@Test
void whenUsingConcat_thenAssertEquals() {
    String stringOne = "Hello";
    String stringTwo = " World";
    assertEquals("Hello World", stringOne.concat(stringTwo));
}

In the previous example, stringOne variable is the base string. With the concat() method, stringTwo is appended at the end of stringOne. The concat() operation is immutable, so we need an explicit assignment. The next example illustrates this case:

在前面的例子中,stringOne变量是基础字符串。通过concat()方法,stringTwo被附加在stringOne的末尾。concat()操作是不可改变的,所以我们需要一个显式赋值。下一个例子说明了这种情况。

@Test
void whenUsingConcatWithOutAssignment_thenAssertNotEquals() {
    String stringOne = "Hello";
    String stringTwo = " World";
    stringOne.concat(stringTwo);
    assertNotEquals("Hello World", stringOne); // we get only Hello
}

Additionally, to get our final concatenated string in this case, we need to assign the concat() result to a variable:

此外,在这种情况下,为了得到我们最终的串联字符串,我们需要将concat()结果分配给一个变量。

stringOne = stringOne.concat(stringTwo);
assertEquals("Hello World", stringOne);

Another useful feature of concat() is when we need to concatenate multiple String objects. This method allows it. Moreover, we can also append space and special characters:

concat()的另一个有用的功能是当我们需要连接多个String对象时。这个方法允许这样做。此外,我们还可以追加空格和特殊字符。

@Test
void whenUsingConcatToMultipleStringConcatenation_thenAssertEquals() {
    String stringOne = "Hello";
    String stringTwo = "World";
    String stringThree = ", in Jav";
    stringOne = stringOne.concat(" ").concat(stringTwo).concat(stringThree).concat("@");
    assertEquals("Hello World, in Jav@", stringOne);
}

What about nulls? Neither the current string nor the string to be appended can be null values. Otherwise, the concat() method throws a NullPointerException:

空值怎么处理?当前的字符串和要追加的字符串都不能是空值。否则,concat()方法抛出一个NullPointerException

@Test
void whenUsingConcatAppendANull_thenAssertEquals() {
    String stringOne = "Hello";
    String stringTwo = null;
    assertThrows(NullPointerException.class, () -> stringOne.concat(stringTwo));
}

2.3. StringBuilder Class

2.3.StringBuilderClass

Firstly, we have the StringBuilder class. This class provides the append() method to perform concatenation operations. The next example shows us how it works:

首先,我们有StringBuilder类。这个类提供了append()方法来执行连接操作。下一个例子向我们展示了它是如何工作的。

@Test
void whenUsingStringBuilder_thenAssertEquals() {
    StringBuilder builderOne = new StringBuilder("Hello");
    StringBuilder builderTwo = new StringBuilder(" World");
    StringBuilder builder = builderOne.append(builderTwo);
    assertEquals("Hello World", builder.toString());
}

On the other hand, a similar concatenation approach is the StringBuffer class. Contrary to the StringBuilder, which is non-synchronized(i.e., not thread-safe), StringBuffer is synchronized(i.e., thread-safe). But it has worse performance than StringBuilder. It has an append() method just like StringBuilder does.

另一方面,类似的连接方法是StringBuffer类。StringBuilder是非同步的(即不是线程安全的),与之相反,StringBuffer是同步的(即是线程安全的)。但它的性能比StringBuilder差。它有一个append()方法,就像StringBuilder那样。

2.4. String format() Method

2.4.字符串format() 方法

Another way to perform string concatenation is using the format() method in the String class. Using format specifiers like %s, we can concatenate multiple strings by their string value or object:

另一种执行字符串连接的方法是使用字符串类中的format()方法。使用像%s,这样的格式指定器,我们可以通过字符串值或对象来连接多个字符串。

@Test
void whenUsingStringFormat_thenAssertEquals() {
    String stringOne = "Hello";
    String stringTwo = " World";
    assertEquals("Hello World", String.format("%s%s", stringOne, stringTwo));
}

2.5. Approaches to Concatenation in Java 8 and Above

2.5.Java 8及以上版本中连接的方法

The method join() in the String class, for Java 8 and above, can perform string concatenation. In this case, this method takes as the first argument a delimiter used between the strings that’ll be concatenated:

Java 8及以上版本的String 类中的join()方法,可以执行字符串连接。在这种情况下,该方法的第一个参数是用于连接的字符串之间的分隔符。

@Test
void whenUsingStringJoin_thenAssertEquals() {
    String stringOne = "Hello";
    String stringTwo = " World";
    assertEquals("Hello World", String.join("", stringOne, stringTwo));
}

Since Java 8, StringJoiner class was added. This class joins Strings using delimiter, prefix, and suffix. The following code snippet is an example of its use:

从Java 8开始,StringJoiner类被添加。这个类使用分隔符、前缀和后缀来连接Strings。下面的代码片段是其使用的一个例子。

@Test
void whenUsingStringJoiner_thenAssertEquals() {
    StringJoiner joiner = new StringJoiner(", ");
    joiner.add("Hello");
    joiner.add("World");
    assertEquals("Hello, World", joiner.toString());
}

Additionally, in Java 8, with the addition of the Stream API, we can find Collectors. The Collectors class has the joining() method. This method works similarly to the join() method in the String class. It’s used for collections. The following example code snippet shows us how it works:

此外,在Java 8中,随着Stream API的增加,我们可以找到CollectorsCollectors类有joining()方法。这个方法的工作原理类似于String类中的join()方法。它被用于集合。下面的示例代码片断向我们展示了它是如何工作的。

@Test
void whenUsingCollectors_thenAssertEquals() {
    List<String> words = Arrays.asList("Hello", "World");
    String collect = words.stream().collect(Collectors.joining(", "));
    assertEquals("Hello, World", collect);
}

3. Choosing an Approach

3.选择一种方法

Finally, if we need to choose between the concat() method and the “+” operator, we need to consider some aspects.

最后,如果我们需要在 concat()方法和”+“操作符之间做出选择,我们需要考虑一些方面。

First, the concat() method only accepts strings. Meanwhile, the “+” operator takes any type and converts it to a string. On the other hand, the concat() method raises a NullPointerExeption on null values, which is not so with the “+” operator.

首先,concat()方法只接受字符串。同时,”+“操作符接受任何类型并将其转换为字符串。另一方面,concat()方法在空值上会引发NullPointerExeption,而”+“操作符则不会这样。

Moreover, there’s a performance difference between both. The concat() method performs better than the “+” operator. The latter always creates a new string irrespective of the length of the string. Additionally, we need to take into account that the concat() method only creates a new string when the string to be appended has a length greater than 0. Otherwise, it returns the same object.

此外,两者之间存在性能差异。concat()方法比”+“操作符表现得更好。后者总是创建一个新的字符串,而不考虑字符串的长度。此外,我们需要考虑到,concat()方法只在要追加的字符串的长度大于0时创建一个新的字符串。 否则,它返回相同的对象。

4. Conclusion

4.总结

In this article, we did a quick overview of string concatenation in Java. Additionally, we discussed in detail the use of concat() and the “+” operator to perform string concatenations. Finally, we performed a comparative analysis between the concat() method and the “+” operator and how we can choose one of them in different contexts.

在这篇文章中,我们对Java中的字符串连接做了一个快速概述。此外,我们详细讨论了使用concat()和”+“操作符来执行字符串连接。最后,我们对concat()方法和”+“操作符进行了比较分析,以及我们如何在不同情况下选择其中之一。

As always, all snippets used in this article are available over on GitHub.

一如既往,本文中所使用的所有片段都可以在GitHub上找到