Java String join()

The java.lang.string.join() method concatenates the given elements with the delimiter and returns the concatenated string.Note that if an element is null, then null is added.The join() method is included in java string since JDK 1.8.

There are two types of join() methods in java string.

Syntax:
public static String join(CharSequence deli, CharSequence... ele) and public static String join (CharSequence deli, Iterable ele) Parameters: deli- delimiter to be attached with each element ele- string or char to be attached with delimiter Returns : string joined with delimiter.
Parameters
delimiter : char value to be added with each element elements : char value to be attached with delimiter
Returns
joined string with delimiter
Throws
NullPointerException if element or delimiter is null.
Java String join() method example
class Test { public static void main(String args[]) { // delimiter is "<" and elements are "Four", "Five", "Six", "Seven" String g1 = String.join(" < ", "Four", "Five", "Six", "Seven"); System.out.println(g1); } }


Output:
Four < Five < Six < Seven
Java String join() method example
class Test { public static void main(String args[]) { // delimiter is " " and elements are "My", // "name", "is", "Rama", "krishna" String g1 = String.join(" ", "My", "name", "is", "Rama", "krishna"); System.out.println(g1); } }


Output:
My name is Rama krishna
Java String join() method example
class Test { public static void main(String args[]) { // delimiter is "->" and elements are "Wake up", // "Eat", "Play", "Sleep", "Wake up" String g1 = String.join("-> ", "Wake up", "Eat", "Play", "Sleep", "Wake up"); System.out.println(g1); } }


Output:
Wake up-> Eat-> Play-> Sleep-> Wake up
Java String join() method example
public class Test { public static void main(String args[]) { String joinS1=String.join("-","welcome","to","cprogramcoding"); System.out.println(joinS1); } }


Output:
welcome-to-cprogramcoding
Java String join() method example

We can use delimeter to format the string as we did in the below example to show date and time.

public class Test { public static void main(String[] args) { String date = String.join("/","09","09","2018"); System.out.print(date); String time = String.join(":", "09","14","08"); System.out.println(" "+time); } }


Output:
09/09/2018 09:14:08



Instagram