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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/format("`Format`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ProgrammingTechniquesGroup -.-> java/lambda("`Lambda`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/FileandIOManagementGroup -.-> java/nio("`NIO`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/StringManipulationGroup -.-> java/stringbuffer_stringbuilder("`StringBuffer/StringBuilder`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/DataStructuresGroup -.-> java/arrays_methods("`Arrays Methods`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117956{{"`Java String Concatenation`"}} java/format -.-> lab-117956{{"`Java String Concatenation`"}} java/generics -.-> lab-117956{{"`Java String Concatenation`"}} java/inner_classes -.-> lab-117956{{"`Java String Concatenation`"}} java/classes_objects -.-> lab-117956{{"`Java String Concatenation`"}} java/class_methods -.-> lab-117956{{"`Java String Concatenation`"}} java/exceptions -.-> lab-117956{{"`Java String Concatenation`"}} java/lambda -.-> lab-117956{{"`Java String Concatenation`"}} java/modifiers -.-> lab-117956{{"`Java String Concatenation`"}} java/oop -.-> lab-117956{{"`Java String Concatenation`"}} java/packages_api -.-> lab-117956{{"`Java String Concatenation`"}} java/nio -.-> lab-117956{{"`Java String Concatenation`"}} java/identifier -.-> lab-117956{{"`Java String Concatenation`"}} java/stringbuffer_stringbuilder -.-> lab-117956{{"`Java String Concatenation`"}} java/arrays -.-> lab-117956{{"`Java String Concatenation`"}} java/comments -.-> lab-117956{{"`Java String Concatenation`"}} java/data_types -.-> lab-117956{{"`Java String Concatenation`"}} java/operators -.-> lab-117956{{"`Java String Concatenation`"}} java/output -.-> lab-117956{{"`Java String Concatenation`"}} java/strings -.-> lab-117956{{"`Java String Concatenation`"}} java/variables -.-> lab-117956{{"`Java String Concatenation`"}} java/arrays_methods -.-> lab-117956{{"`Java String Concatenation`"}} java/object_methods -.-> lab-117956{{"`Java String Concatenation`"}} java/string_methods -.-> lab-117956{{"`Java String Concatenation`"}} java/system_methods -.-> lab-117956{{"`Java String Concatenation`"}} end

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