English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String join() method returns a new string that has the specified elements and delimiter.
Syntax of the string join() method:
String.join(CharSequence delimiter, Iterable elements)
or
String.join(CharSequence delimiter, CharSequence... elements)
Here, ... indicates that one or more CharSequence (character sequences) can be present.
Note: join() is a static method. You do not need to create a string object to call this method. Instead, we use the class name String to call this method.
delimiter - Delimiter used to connect elements
elements - Elements to be connected
Returns a string
class Main { public static void main(String[] args) { String result; result = String.join("-"Java", "is", "fun"; System.out.println(result); // Java-is-fun } }
Here, we passed three strings Java, is, and fun to the join() method. These strings are connected using-connected using delimiters.
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> text = new ArrayList<>(); //Adding elements to the ArrayList text.add("Java"); text.add("is"); text.add("fun"); String result; result = String.join("-", text); System.out.println(result); // Java-is-fun } }
Here, we will create an ArrayList of String type. The elements of the ArrayList use-connected using delimiters.