HelloKoding

Practical coding guides

Join and concat strings in Java

In Java, you can join strings with StringJoiner and String.join(), concat strings with StringBuilder, StringBuffer, String.concat method and + operator

Join strings with StringJoiner

StringJoiner is used to join a sequence of strings by a delimiter

@Test
public void joinWithStringJoiners() {
    StringJoiner stringJoiner = new StringJoiner(", ");

    stringJoiner.add("apple")
        .add("orange")
        .add("passion");

    String result = stringJoiner.toString();

    assertThat(result).isEqualTo("apple, orange, passion");
}

Join strings with String.join method

String.join method is used to join an array or any Iterable collections like List or Set of strings by a delimiter

@Test
public void joinArrayOfStringsWithStringJoin() {
    String[] arr = {"apple", "orange", "passion"};

    String result = String.join(", ", arr);

    assertThat(result).isEqualTo("apple, orange, passion");
}

@Test
public void joinListOfStringsWithStringJoin() {
    List<String> lst = Arrays.asList("apple", "orange", "passion");

    String result = String.join(", ", lst);

    assertThat(result).isEqualTo("apple, orange, passion");
}

@Test
public void joinSetOfStringsWithStringJoin() {
    Set<String> set = new LinkedHashSet<>(Arrays.asList("apple", "orange", "passion"));

    String result = String.join(", ", set);

    assertThat(result).isEqualTo("apple, orange, passion");
}

Concat strings with StringBuilder

You can use StringBuilder’s append or insert method to concatenate strings. They are overloaded to accept any data type. While append method always adds the string at the end of the builder, the insert method adds the string at a specified index

Instances of StringBuilder are not safe to be used by multiple threads. In that case, consider using StringBuffer

@Test
public void givenMultipleDataTypes_whenConcatByStringBuilder_thenSuccess() {
    StringBuilder sb = new StringBuilder();
    sb.append("Hello ");
    sb.append("Koding ");
    sb.append(2015);
    String result = sb.toString();

    assertThat(result).isEqualTo("Hello Koding 2015");
}

Concat strings with SpringBuffer

StringBuffer has the API compatible with StringBuilder, so you can also use append or insert methods of StringBuffer to concatenate strings

StringBuffer is designed to be used in multiple threads environment

@Test
public void givenMultipleDataTypes_whenConcatByStringBuilder_thenSuccess() {
    StringBuffer sb = new StringBuffer();
    sb.append("Hello ");
    sb.append("Koding ");
    sb.append(2015);
    String result = sb.toString();

    assertThat(result).isEqualTo("Hello Koding 2015");
}

Concat strings with String.concat method

The Java String class provides the concat(String) method to concatenate the specified string to the end of the caller string

The concat method only accept String data type, so try converting the argument to String before passing to the method

@Test
public void givenMultipleDataTypes_whenConcatByStringConcat_thenSuccess() {
    int foundedYear = 2015;
    String result = "Hello ".concat("Koding ").concat(Integer.toString(foundedYear));

    assertThat(result).isEqualTo("Hello Koding 2015");
}

Concat strings with + operator

The Java + operator will try to convert the input parameters to String before concatenation. It offers convenient typing but with slowest performance as a new String object will be created on every operation

@Test
public void givenMultipleDataTypes_whenConcatByPlus_thenSuccess() {
    int foundedYear = 2015;
    String result = "Hello " + "Koding " + foundedYear;

    assertThat(result).isEqualTo("Hello Koding 2015");
}

Conclusion

In this tutorial, we learned various methods to join and concat strings in Java. While StringJoiner and String’s join methods support to join strings with delimiter, other methods offer the flexibility. You can find the full source code as below

StringJoiningTest.java

package com.hellokoding.java.lang;

import org.junit.Test;

import java.util.*;

import static org.assertj.core.api.Assertions.assertThat;

public class StringJoiningTest {
    @Test
    public void joinStringsWithStringJoiners() {
        StringJoiner stringJoiner = new StringJoiner(", ");

        stringJoiner.add("apple")
            .add("orange")
            .add("passion");

        String result = stringJoiner.toString();

        assertThat(result).isEqualTo("apple, orange, passion");
    }

    @Test
    public void joinArrayOfStringsWithStringJoin() {
        String[] arr = {"apple", "orange", "passion"};

        String result = String.join(", ", arr);

        assertThat(result).isEqualTo("apple, orange, passion");
    }

    @Test
    public void joinListOfStringsWithStringJoin() {
        List<String> lst = Arrays.asList("apple", "orange", "passion");

        String result = String.join(", ", lst);

        assertThat(result).isEqualTo("apple, orange, passion");
    }

    @Test
    public void joinSetOfStringsWithStringJoin() {
        Set<String> set = new LinkedHashSet<>(Arrays.asList("apple", "orange", "passion"));

        String result = String.join(", ", set);

        assertThat(result).isEqualTo("apple, orange, passion");
    }

    @Test
    public void joinStringsWithStringConcat() {
        String joinedString = "apple"
            .concat(", ")
            .concat("orange")
            .concat("; ")
            .concat("passion");

        assertThat(joinedString).isEqualTo("apple, orange; passion");
    }
}
Follow HelloKoding