What is String.join() in Java?

The String.join() method is a static method in the String class that concatenates one or more strings with a delimiter added between each String. This method joins the passed string with the delimiter passed to return a single string.

Syntax

// For strings
String join(CharSequence delimiter, CharSequence... elements)

// For iterable objects like ArrayList, HashSet
String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

Example

class Main {
public static void main( String args[] ) {
String delimiter = "-";
String result = String.join(delimiter, "Edpresso", "is", "Good");
System.out.println(result);
}
}

In the code above, we call the String.join method with three strings and with the delimiter -. The String.join method concatenates all the strings passed with the delimiter added between the strings, and returns the concatenated string.

Example with iterable objects

import java.util.ArrayList;
class Main {
public static void main( String args[] ) {
String delimiter = "-";
ArrayList<String> msg = new ArrayList<>();
msg.add("Educative");
msg.add("is");
msg.add("Informative");
String result = String.join(delimiter, msg);
System.out.println(result);
}
}

In the code above, we create an ArrayList with three elements and call the String.join() method with the created ArrayList and delimiter String -. The String.join() method concatenates all the strings in the iterable with the delimiter added between the strings, and returns the concatenated string.

Free Resources