[Java] How to concatenate strings in Java

This article is for learning reference only!

Java programming tutorial

String concatenation can be defined as the process of joining two or more strings together to form a new string. Most programming languages ​​provide at least one way to concatenate strings. Java gives you a variety of options, including:

  • **+** operator
  • **String. concat()** method
  • StringBuilder class
  • StringBuffer class

This article describes how to concatenate strings together using each of the four methods above, and provides some tips on how to choose the best method for a given situation.

Use the plus (+) operator

This is the simplest and most common way of concatenating strings in Java. Placing the plus ( + ) operator between two or more strings combines them into an entirely new string. Therefore, the String object produced by concatenation will be stored in a new memory location in the Java heap. However, if a matching string already exists in the string pool, a reference to the found String object is returned . You can think of it as a form of caching. Here is a quick code example of the **+** operator in Java:

String firstName = "Rob";
String lastName  = "Gravelle";
// Outputs "Rob Gravelle"
System.out.println(firstName + " " + lastName);

Advantages of the Plus (+) Operator: Automatic Type Conversion and Null Handling

The + operator automatically converts all native types to their string representations, so it can handle everything from ints , floats , and doubles to single ( char ) characters. Also, it doesn't throw any Null value exception and converts Null to its String representation. Here is some sample code showing how to use the **+** operator for string concatenation in Java:

String fruits = "apples";
int howMany = 4;
String other = null;
// Outputs "I have 4 apples as well as null."
System.out.println("I have " + howMany + " " + fruits + " as well as " + other + ".");

Behind the scenes, the + operator uses the native type's implicit type conversion and the object's toString() method to silently convert non-string data types to String , and that's how it avoids NullPointerException . The only downside is that we'll end up with the word " null " in the resulting string , which is probably not what the developer intended.

String concatenation is implemented through the **append() method of the StringBuilder class. The + operator generates a new string by appending the second operand to the end of the first operand . **In our previous example, Java was doing the following:

String s = (new StringBuilder())
             .append("I have ")
             .append(howMany)
             .append(" ")
             .append(fruits)
             .append(" as well as ")
             .append(other)
             .append(".")
               .toString(); 

Java String Concatenation Tips

Always store the returned string after concatenation with the **+ operator in a variable if you plan to use it again. This will save the programmer from having to go through the concatenation process multiple times. Also, avoid using the +** operator to concatenate strings in a loop, as this causes a lot of overhead.

While convenient, the **+** operator is the slowest way to concatenate strings. The other three options are more efficient, as we'll see next.

Use the String.concat() method

The String.concat method concatenates the specified string to the end of the current string. Its syntax is:

@Test
void concatTest() {
    
    
String str1 = "Hello";
String str2 = " World";
assertEquals("Hello World", str1.concat(str2));
assertNotEquals("Hello World", str1); // still contains "Hello"
}

We can concatenate multiple Strings by chaining consecutive concat calls , like so:

void concatMultiple() {
    
    
String str1 = "Hello";
String str2 = " World";
String str3 = " from Java";
str1 = str1.concat(" ").concat(str2).concat(str3);
System.out.println(str1); //"Hello World from Java";
}

Note that neither the current string nor the string to be appended can contain Null values. Otherwise, the concat method will throw NullPointerException .

StringBuilder and StringBuffer classes

StringBuilder and StringBuffer classes are the fastest way to concatenate strings in Java . As such, they are ideal for concatenating large numbers of strings -- especially in loops. The two classes behave in much the same way, with the main difference being that StringBuffer is thread-safe while StringBuilder is not. Both classes provide an **append()** method to perform the concatenation operation. The append() method is overloaded to accept parameters of many different types such as Objects , StringBuilder , int , char , CharSequence , boolean , float , double , etc.

In addition to the performance benefits, StringBuffer and StringBuilder provide a mutable alternative to the immutable String class. Unlike the String class , which contains fixed-length, immutable character sequences , StringBuffer and StringBuilder have scalable length and modifiable character sequences.

Here's an example of concatenating an array of ten integers using StringBuilder and StringBuffer :

import java.util.stream.IntStream;
import java.util.Arrays;

public class StringBufferAndStringBuilderExample {
    
    
  public static void main(String[] args) {
    
    
    // Create an array from 1 to 10
    int[] range = IntStream.rangeClosed(1, 10).toArray();
    
    // using StringBuilder
    StringBuilder sb = new StringBuilder();
    for (int num : range) {
    
    
      sb.append(String.valueOf(num));
    }
    System.out.println(sb.toString()); // 12345678910
    
    // using StringBuffer
    StringBuffer sbuf = new StringBuffer();
    for (int num : range) {
    
    
      sbuf.append(String.valueOf(num));
    }
    System.out.println(sbuf.toString()); // 12345678910
  }
}

END

In this article, we've taken a comprehensive look at Java's four main ways of concatenating strings together, along with tips on how to choose the best method for a given situation. All in all, when you need to choose between the **+ operator, the concat method, and the StringBuilder/StringBuffer classes, consider whether you're dealing with strings alone or with mixed data types. You should also consider the possibility of NullPointerExeptions on Null values . Finally, there are issues of performance and variability. The + operator is the slowest of all the options I've seen today, while the StringBuilder and StringBuffer** classes are both fast and mutable.

If you really want to see all the concatenation options in Java, version 8 introduces more methods for concatenating Strings , including the String.join() method and the StringJoiner class. Version 8 also introduces Collectors . The Collectors class has a join() method that works very similarly to the **join()** method of the String class.

Guess you like

Origin blog.csdn.net/m0_47015897/article/details/131410376