The join() method returns a new string with the given elements joined with the specified delimiter.
Example
Syntax of join()
The syntax of the string join() method is either:
String.join(CharSequence delimiter,
Iterable elements)
or
String.join(CharSequence delimiter,
CharSequence... elements)
Here, ... signifies there can be one or more CharSequence.
Note: join() is a static method. You do not need to create a string object to call this method. Rather, we call the method using the class name String.
join() Parameters
The join() method takes two parameters.
- delimiter - the delimiter to be joined with the elements
- elements - elements to be joined
Notes:
- You can pass any class that implements
CharSequencetojoin(). - If an iterable is passed, its elements will be joined. The iterable must implement
CharSequence. - String, StringBuffer, CharBuffer etc. are CharSequence as these classes implement it.
join() Return Value
- returns a string
Example 1: Java String join() With CharSequence()
Here, we have passed three strings Java, is and fun to the join() method. These strings are joined using the - delimiter.
Example 2: Java String join() With Iterable
Here, an ArrayList of String type is created. The elements of array list are joined using the - delimiter.