Java Data Type How to - Join several Strings into a long string








Question

We would like to know how to join several Strings into a long string.

Answer

static join() method joins multiple strings into one string. It is overloaded.

String  join(CharSequence delimiter, CharSequence... elements)
String  join(CharSequence delimiter,  Iterable<? extends CharSequence>  elements)

The first version takes a delimiter and a sequence of strings to be joined.

The second version takes a delimiter and an Iterable, for example, a List or Set.

The following code uses the first version to join some strings:

String str = String.join(",", "A",  "F", "N", "C", "A"); 
System.out.println(str);