Java String Concatenation

JavaJavaBeginner
Practice Now

Introduction

Concatenation is the process of combining two or more strings into a single string. In Java, there are several ways to concatenate strings. Each method has its advantages and disadvantages depending on the requirements. This lab will cover the various ways by which we can concatenate strings in Java.

Concatenate Strings using + Operator

The simplest method of combining strings in Java is by using the + operator. The + operator is overloaded to work with strings. Follow the code block below to see how to concatenate strings using the + operator.

public class ConcatenateStrings {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "World";
        String combination = a + " " + b;   // Using + operator to concatenate strings
        System.out.println(combination);    // Output: Hello World
    }
}

Concatenate Strings using StringBuilder Class

Another way to concatenate strings in Java is by using the StringBuilder class. The StringBuilder class provides append() method to combine two or more strings. StringBuilder is faster than String class while concatenating strings. Follow the code block below on how to concatenate strings using the StringBuilder class.

public class ConcatenateStrings {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "World";
        StringBuilder builder = new StringBuilder();
        builder.append(a).append(" ").append(b);   // Using StringBuilder class to concatenate strings
        String combination = builder.toString();
        System.out.println(combination);   // Output: Hello World
    }
}

Concatenate Strings using StringBuffer Class

Similar to StringBuilder, StringBuffer is also a mutable sequence of characters and provides append() method to append the strings. StringBuffer is synchronized which means multiple threads cannot access it simultaneously.

public class ConcatenateStrings {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "World";
        StringBuffer buffer = new StringBuffer();
        buffer.append(a).append(" ").append(b);   // Using StringBuffer class to concatenate strings
        String combination = buffer.toString();
        System.out.println(combination);   // Output: Hello World
    }
}

Concatenate Strings using String.concat() Method

The concat() method can be used to concatenate two strings. This method internally uses the StringBuilder class to perform concatenation. Follow the code block below on how to use the concat() method to concatenate strings.

public class ConcatenateStrings {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "World";
        String combination = a.concat(" ").concat(b);   // Using String.concat() method to concatenate strings
        System.out.println(combination);   // Output: Hello World
    }
}

Concatenate Strings using String.join() Method

The String.join() method is used to concatenate multiple strings with a delimiter. The first parameter of String.join() is the delimiter that needs to be added between the strings. This method works from Java 8 onwards. Follow the code block below to see how to concatenate strings using String.join() method.

public class ConcatenateStrings {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "World";
        String c = "Java";
        String combination = String.join(" ", a, b, c);   // Using String.join() method to concatenate strings
        System.out.println(combination);   // Output: Hello World Java
    }
}

Concatenate Strings using String.format() Method

The String.format() method returns a formatted string. It takes the format string as the first parameter to which the string variables need to be concatenated. It works similar to printf function in C. Follow the code block below on how to use the String.format() method to concatenate strings.

public class ConcatenateStrings {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "World";
        String c = "Java";
        String combination = String.format("%s %s %s", a, b, c);  // Using String.format() method to concatenate strings
        System.out.println(combination);   // Output: Hello World Java
    }
}

Concatenate Strings using Arrays.toString() Method

The Arrays.toString() method is used to return a string that represents the contents of the array. Follow the code block below to see how to use the Arrays.toString() method to concatenate an array of strings.

import java.util.Arrays;
public class ConcatenateStrings {
    public static void main(String[] args) {
        String[] strings = {"Hello", "World", "Java"};
        String combination = Arrays.toString(strings);   // Using Arrays.toString() method to concatenate an array of strings
        System.out.println(combination);   // Output: [Hello, World, Java]
    }
}

Concatenate Strings using StringJoiner Class

The StringJoiner class is used to join strings with a delimiter. The StringJoiner class is available from Java 8 onwards. In the following example, weโ€™re going to use the StringJoiner class to concatenate three strings with a delimiter. Follow the code block below on how to use the StringJoiner class to concatenate strings.

import java.util.StringJoiner;
public class ConcatenateStrings {
    public static void main(String[] args) {
        StringJoiner joiner = new StringJoiner(" ");
        joiner.add("Hello");  // Using StringJoiner class to concatenate strings
        joiner.add("World");
        joiner.add("Java");
        String combination = joiner.toString();
        System.out.println(combination);   // Output: Hello World Java
    }
}

Concatenate Strings using Collection.join() Method

We can also use the join() method of the Collections class to concatenate a list of strings. Follow the code block below to see how to use the Collections.join() method to concatenate a list of strings.

import java.util.Arrays;
import java.util.List;
import java.util.Collections;
public class ConcatenateStrings {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("Hello", "World", "Java");
        String separator = " ";
        String combination = String.join(separator, strings);   // Using Collections.join() method to concatenate a list of strings
        System.out.println(combination);   // Output: Hello World Java
    }
}

Concatenate Strings using Files.lines() Method

We can also use the Files.lines() method introduced in Java 8 to concatenate strings. Follow the code block below to see how to use the Files.lines() method to concatenate strings.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class ConcatenateStrings {
    public static void main(String[] args) {
        try {
            String combination = Files.lines(Paths.get("file1.txt"))
                                      .reduce("", (line1, line2) -> line1 + line2);
            System.out.println(combination);
        } catch (IOException exception) {
            System.out.println("Exception Occurred: " + exception);
        }
    }
}

Note: The above code block reads the contents from a file named file1.txt and concatenates the contents into a single string.

Summary

In summary, there are many ways to concatenate strings in Java. In this lab, we have covered various methods such as + operator, StringBuilder class, StringBuffer class, String.concat() method, String.join() method, String.format() method, Arrays.toString() method, StringJoiner class, Collections.join() method, and Files.lines() method. It is necessary to understand the nuances of each method and use it as appropriate to obtain the desired result.

Other Java Tutorials you may like