Concatenate Strings In Java - 6 Ways to Concatenate Strings In Java

In this article, we will discuss several ways of concatenating Strings in Java and also outline some common pitfalls and bad practices.
String concatenation is the process of joining two or more small String to create a big String. For example, you can create a full name by concatenating first and last name of a person.

Different Ways to concatenating Strings In Java

  1. Using StringBuilder
  2. Addition(+) Operator
  3. Using String.concat() Method
  4. Using String.join() Method (Java 8+)
  5. Using StringJoiner Class (Java 8+)
  6. Using Arrays.toString() Method
Let's discuss the above different ways to concatenating Strings in Java.

1. Using StringBuilder

StringBuilder class provides append() method which is used to append the specified string to this character sequence. Let’s build a quick example of String concatenation using the StringBuilder class:
package com.javaguides.corejava.string;

public class ConcatStringExample {
    public static void main(String[] args) {
        ConcatStringExample example = new ConcatStringExample();
        example.usingStringBuilder();
    }
    public void usingStringBuilder() {
        StringBuilder stringBuilder = new StringBuilder(150);
        stringBuilder.append("Java");
        stringBuilder.append(" is");
        stringBuilder.append(" top");
        stringBuilder.append(" programming");
        stringBuilder.append(" laguange");
        System.out.println(stringBuilder.toString());
    }
}
Output:
Java is top programming laguange
Internally, StringBuilder maintains a mutable array of characters. In our code sample, we’ve declared this to have an initial size of 150 through the StringBuilder constructor. Because of this size declaration, the StringBuilder can be a very efficient way to concatenate Strings.
It’s also worth noting that the StringBuffer class is the synchronized version of StringBuilder. Although synchronization is often synonymous with thread safety, it’s not recommended for use in multithreaded applications due to StringBuffer’s builder pattern.

2. Addition(+) Operator

This is the same operator that results in the addition of numbers and is overloaded to concatenate when applied to Strings.
If you have more string concatenation operations, then prefer using StringBuilder object over the + operator.
Let’s take a quick look at how this works:
package com.javaguides.corejava.string;

public class ConcatStringExample {

    public static void main(String[] args) {
        ConcatStringExample example = new ConcatStringExample();
        example.usingPlusOperator();
    }

    public void usingPlusOperator() {
        String concatStr = "Java" + " is" + " top" + " programming" + " language";
        System.out.println(concatStr);
    }
}
Output:
Java is top programming language
Notice that String concatenation using the + operator within a loop should be avoided. Since the String object is immutable, each call for concatenation will result in a new String object being created.

3. Using String.concat() Method

Let's use Spring.concat() method -This method concatenates the specified string to the end of this string. This method returns a String object, so chaining together the method is a useful feature.
package com.javaguides.corejava.string;

public class ConcatStringExample {

    public static void main(String[] args) {
        ConcatStringExample example = new ConcatStringExample();
        example.usingStringConcatMethod();
    }

    public void usingStringConcatMethod() {
        String concatStr = "Java".concat(" is").concat(" top").concat(" programming").concat(" language");
        System.out.println(concatStr);
    }
}
Output:
Java is top programming language

4. Using String.join() Method (Java 8+)

If our application is running on Java 8 or above, we can take advantage of the String.join method. With this, we can join an array of Strings with a common delimiter, ensuring no spaces are missed.
package com.javaguides.corejava.string;

public class ConcatStringExample {

    public static void main(String[] args) {
        ConcatStringExample example = new ConcatStringExample();
        example.usingStringJoinMethod();
    }

    public void usingStringJoinMethod() {
        String[] strArray = {
            "Java",
            " is",
            " top",
            " programming",
            " language"
        };
        String concatStr = String.join("", strArray);
        System.out.println(concatStr);
    }
}
Output:
Java is top programming language
A huge advantage of this method is not having to worry about the delimiter between our strings.

5. Using StringJoiner Class (Java 8+)

Java 8 added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create a string by passing delimiters like a comma(,), hyphen(-) etc.
package com.javaguides.corejava.string;

import java.util.StringJoiner;

public class ConcatStringExample {

    public static void main(String[] args) {
        ConcatStringExample example = new ConcatStringExample();
        example.usingStringJoinerClass();
    }

    public void usingStringJoinerClass() {
        StringJoiner joiner = new StringJoiner(" ");
        joiner.add("Java");
        joiner.add("is");
        joiner.add("top");
        joiner.add("programming");
        joiner.add("language");
        System.out.println(joiner.toString());
    }
}
Output:
Java is top programming language

6. Using Arrays.toString() Method

The Array class contains a handy toString method which nicely formats an array of objects. The Arrays.toString method also calls the toString method of any enclosed object – so we need to ensure we have one defined.
package com.javaguides.corejava.string;

import java.util.Arrays;

public class ConcatStringExample {

    public static void main(String[] args) {
        ConcatStringExample example = new ConcatStringExample();
        example.usingArrayToString();
    }

    public void usingArrayToString() {
        String[] myFavouriteLanguages = {
            "Java",
            "C",
            "Java EE"
        };

        String str = Arrays.toString(myFavouriteLanguages);

        System.out.println(str);
    }
}
Output:
[Java, C, Java EE]

Complete Example

package com.javaguides.corejava.string;

import java.util.Arrays;
import java.util.StringJoiner;

public class ConcatStringExample {

    public static void main(String[] args) {
        ConcatStringExample example = new ConcatStringExample();
        example.usingArrayToString();
        example.usingStringBuilder();
        example.usingPlusOperator();
        example.usingStringConcatMethod();
        example.usingStringJoinerClass();
        example.usingStringJoinMethod();
    }

    public void usingStringBuilder() {
        StringBuilder stringBuilder = new StringBuilder(150);
        stringBuilder.append("Java");
        stringBuilder.append(" is");
        stringBuilder.append(" top");
        stringBuilder.append(" programming");
        stringBuilder.append(" laguange");
        System.out.println(stringBuilder.toString());
    }

    public void usingPlusOperator() {
        String concatStr = "Java" + " is" + " top" + " programming" + " language";
        System.out.println(concatStr);
    }

    public void usingStringConcatMethod() {
        String concatStr = "Java".concat(" is").concat(" top").concat(" programming").concat(" language");
        System.out.println(concatStr);
    }

    public void usingStringJoinMethod() {
        String[] strArray = {
            "Java",
            " is",
            " top",
            " programming",
            " language"
        };
        String concatStr = String.join(" ", strArray);
        System.out.println(concatStr);
    }

    public void usingStringJoinerClass() {
        StringJoiner joiner = new StringJoiner("");
        joiner.add("Java");
        joiner.add("is");
        joiner.add("top");
        joiner.add("programming");
        joiner.add("language");
        System.out.println(joiner.toString());
    }

    public void usingArrayToString() {
        String[] myFavouriteLanguages = {
            "Java",
            "C",
            "Java EE"
        };

        String str = Arrays.toString(myFavouriteLanguages);

        System.out.println(str);
    }
}
Output:
[Java, C, Java EE]
Java is top programming laguange
Java is top programming language
Java is top programming language
Javaistopprogramminglanguage
Java  is  top  programming  language

Related Java String Programs and Examples

Comments