Joining Strings

JDK 8 added a new method to String called join(). It is used to concatenate two or move strings, separating each string with a delimiter, such as space or a comma. It has two forms. Its first is shown here :

static String join(CharSequence d, CharSequence ...str)

Here, "d" specifies the delimiter used to separate the character sequences specified by "str". Because String implements the CharSequence interface, "str" can be a list of strings. The following program shows this version of join():


public class Main 
  public static void main(String[] args) 
    String numbers = String.join(" , ","1","2","3","4");
    String mobiles = String.join(" | ","redmi","realme","samsung");

In the first call to join(), space is inserted between each string. In the second call, the delimiter is a comma followed by space. This illustrates that the delimiter need not be just a single character.

The second form of join() allows you to join a list of strings derived from an object that applies the interface to the item.