In computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "my" and "Compiler" would result in the string "myCompiler". In Java, there are multiple ways to concatenate strings as we will see below.

Using the Concatenation Operator

The concatenation operator (+) can be used to concatenate two or more strings. For example, the following code will concatenate the strings "Hello" and "World":

String str1 = "Hello";
String str2 = "World";
String str3 = str1 + str2;

System.out.println(str3); // prints: HelloWorld

This will print "HelloWorld" to the console.

If we want to add a space between the strings, we can do so by concatenating a space character:

String str1 = "Hello";
String str2 = "World";
String str3 = str1 + " " + str2;

System.out.println(str3); // prints: Hello World

This will print "Hello World" to the console.

We can also use the increment operator (+=) to join two strings:

String str1 = "Hello";
String str2 = "World";
str1 += str2;

System.out.println(str1); // prints: HelloWorld

We can also concatenate other data types with strings. For example, we can concatenate an integer with a string:

String str1 = "The answer is: ";
int num = 48;
String str2 = str1 + num;

System.out.println(str2); // prints: The answer is: 48

This will print "The answer is: 48" to the console. Note that the number is automatically converted to a string before it is concatenated.

This method works for other data types as well, as long as the class defining the data type has a toString() method. The toString() method is used to convert a non-string data type to a string.

Using the concat() method

The concat() method is a function available in the String class. It takes in a single string parameter, and returns a new string. The new string is the concatenation of the string object whose concat() method was called, and the string argument provided to the concat() method.

Here is a simple example of using the concat() method:

String s1 = "my";
String s2 = "Compiler";

String s3 = s1.concat(s2);
System.out.println(s3); // prints: myCompiler

Since the concat() method returns a new string, we can call concat() on the returned string to concatenate yet another string. Consider the example below:

String s1 = "my";
String s2 = "Compiler";
String s3 = "!";

String s4 = s1.concat(s2).concat(s3);
System.out.println(s4); // prints: myCompiler!

Here, s1.concat(s2) returns the String object with the text "myCompiler". Now, we call the concat(s3) on the intermediate string object returned by calling s1.concat(s2). We end up with a new String object with the text "myCompiler!", and we store it in the variable s4.

Using the StringBuilder class

String objects in Java are immutable. This means, when you use the + operator, the += operator, or the .concat() method, Java creates a new String object in memory, which stores the concatenated value. However, the old String object is still held in memory and only freed up during a garbage collection cycle.

Thus, it is not efficient to use the above methods when concatenating a large number of strings. The StringBuilder class provides a more efficient way to concatenate strings in Java. StringBuilder stores a mutable sequence of characters. This means that we can change the value of a StringBuilder object after it has been created, and additional objects are not created on every concatenation.

The StringBuilder class has a number of methods for concatenating strings. The append() method can be used to concatenate one or more strings:

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");

String s = sb.toString();
System.out.println(s); // prints: Hello World

The above program will print "Hello World" to the console.

The insert() method can be used to insert a string at a specific index. In this example, we add "Hello World" to the StringBuilder object, and then insert "great " at index 6, in between "Hello" and "World".

StringBuilder sb = new StringBuilder();
sb.append("Hello World");
sb.insert(6, "great ");

String s = sb.toString();
System.out.println(s); // prints: Hello great World

The above program will print "Hello great World" to the console.

We can also concatenate the elements of a list, by iterating the elements of the list and adding them to the StringBuilder object:

List<String> list = Arrays.asList("One", "Two", "Three");
StringBuilder sb = new StringBuilder();

for (String element: list) {
  sb.append(element);
}

String s = sb.toString();
System.out.println(s); // prints: OneTwoThree

We can also use the forEach() method provided in the list interface to simplify the above program. The forEach() method takes a lambda expression or method, and calls it with each element of the list.

List<String> list = Arrays.asList("One", "Two", "Three");
StringBuilder sb = new StringBuilder();

list.forEach(sb::append);
String s = sb.toString();
System.out.println(s); // prints: OneTwoThree

Using the format() method

The format() method takes a variable number of arguments, each of which is a string. The first string is the "format string" which contains text and placeholders for the other strings. The placeholders are represented by %s, and each placeholder will be replaced by the next string in the list. For example, consider the following code:

String s1 = "Hello";
String s2 = "World";
String s3 = String.format("%s, %s!", s1, s2);

System.out.println(s3); // prints: Hello, World!

In this example, the format string is "%s, %s!", which contains two placeholders. These placeholders will be replaced by s1 and s2, in that order. The resulting string will be "Hello, World!".

Using the String.join() method

Suppose we have an array or list or strings, and we want to join all the elements into a single string. Java provides a String.join() method for this purpose. It takes in a delimiter (separator string) string as its first argument, and an iterable (list or array) of strings as its second argument. It returns a string where every element of the iterable is concatenated with the delimiter string in between.

For example, if we have a list of strings, we can concatenate them together into a single string, separated by ", ", like this:

List<String> list = Arrays.asList("One", "Two", "Three");

String s = String.join(", ", list);
System.out.println(s); // prints: One, Two, Three

This would give us a string with the value "One, Two, Three".

We can specify the empty string "" as a delimiter if we wish to concatenate the string without a delimiter in between:

List<String> list = Arrays.asList("One", "Two", "Three");

String s = String.join("", list);
System.out.println(s); // prints: OneTwoThree

Using the StringJoiner class

StringJoiner is a new class introduced in Java 8. We can add multiple strings to a StringJoiner object, and then we can obtain a concatenated string that is separated by a delimiter string.

In this example, we initialize a StringJoiner object with the delimiter ", ". Then, we add three strings to it and convert the stringJoiner object to a string, resulting in the string "Java, StringJoiner, Example".

StringJoiner stringJoiner = new StringJoiner(", ");
stringJoiner.add("Java");
stringJoiner.add("StringJoiner");
stringJoiner.add("Example");

String s = stringJoiner.toString();
System.out.println(s); // prints: Java, StringJoiner, Example

We can also specify the prefix and suffix to be used while concatenating the strings. In the example below, we have used ", " as the delimiter string, "[" as the prefix, and "]" as the suffix.

StringJoiner stringJoiner = new StringJoiner(", ", "[", "]");
stringJoiner.add("Java");
stringJoiner.add("StringJoiner");
stringJoiner.add("Example");

String s = stringJoiner.toString();
System.out.println(s); // prints: [Java, StringJoiner, Example]

We can use a for loop to join the elements of a list or array using the StringJoiner class, as shown below:

List<String> list = Arrays.asList("Java", "StringJoiner", "Example");
StringJoiner stringJoiner = new StringJoiner(", ");

for (String element: list) {
  stringJoiner.add(element);
}

String s = stringJoiner.toString();
System.out.println(s); // prints: Java, StringJoiner, Example

Using the Collectors.joining() method

In Java, the Collectors.joining() method can be used to concatenate strings present as part of a Java stream.

The Collectors.joining() method has two versions — the first version joins strings as-is, and the second version joins strings separated by delimiters. Their usage is demonstrated below. s1 stores the concatenation of the string "a", "b", and "c", whereas s2 stores the concatenation separated by the delimiter ", ".

List<String> list = Arrays.asList("One", "Two", "Three");

// without a delimiter
String s1 = list.stream().collect(Collectors.joining());
System.out.println(s1); // prints OneTwoThree

// with a delimiter
String s2 = list.stream().collect(Collectors.joining(","));
System.out.println(s2); // prints One,Two,Three

Since Collectors.joining() works with streams, we have the power of the Stream API at our disposal. As an example, if we have a list of strings and we want to obtain the concatenation of only those strings which start with the character "T". Once we've converted the list to a stream, we can provide a lambda expression x -> x.startsWith("T") to the filter() method to select the elements matching said condition, before concatenating them with Collectors.joining().

In the example below, the strings "Two" and "Three" satisfy this condition, but "One" doesn't. So, the concatenated output is "TwoThree".

List<String> list = Arrays.asList("One", "Two", "Three");

String s1 = list.stream()
  .filter(x -> x.startsWith("T"))
  .collect(Collectors.joining());

System.out.println(s1); // prints: TwoThree