How to concatenate a String in Java

Using the + operator:

The main way to concatenate two String in Java is using the + operator. It creates a new String Object using the 2 Strings as input. This method is memory intensive as a new String Object is created and adds more load on the garbage collection.

    String out = "aa" + " " + "bb";
    System.out.println(out);

Using a StringBuilder:

A StringBuilder doesn't create a new Object every time a String is added to the current String and is not synchronized. It gives better performance.

    StringBuilder sb = new StringBuilder();
    sb.append("aa");
    sb.append(" ");
    sb.append("bb");

    String out = sb.toString();
    System.out.println(out);

Using a StringJoiner:

Since Java 8, a StringJoiner concatenates Strings using a value separator. It's usage is similar to using a list.

    StringJoiner sj = new StringJoiner(" ");
    sj.add("aa");
    sj.add("bb");
    String out = sj.toString();

The StringJoiner can be used in conjunction with a List: It is converted to a Stream. That Stream is then collected using a StringJoiner and a String is returned.

    List<String> l = new ArrayList<>();
    l.add("aa");
    l.add("bb");

    String out = l.stream().collect(Collectors.joining(" "));

References:

Java String

Recent Comments