Java String join:

The join() method in Java joins the string with the given delimiter and returns an updated string. The first argument passed in this method is a delimiter and the rest of the arguments are the strings that will be joined with the delimiter.

The join() method was introduced as part of the Java8 release.

Method signature:

The signature for a join() method is as shown below.

public static String join(CharSequence delimiter, CharSequence... elements)

Method parameters and return type:

Return type: It returns a string joined with a given delimiter

Parameters: It takes CharSequence delimiter and elements as a parameter.

Throws: It throws a NullPointerException if the element of the delimiter is null.

Example 1:

Here we passed a comma as a delimiter and we have joined the rest of the string with it. Let’s check the source to understand this concept.

Source code:

public class Example1 {

    public static void main(String args[]) {
        String str = String.join(",", "This", "is", "Java", "Tutorial");
        System.out.println(str);
    }
}

Output:

run:
This,is,Java,Tutorial
BUILD SUCCESSFUL (total time: 1 second)

Example 2:

In case you are passing null as a delimiter, the program will generate a null pointer exception. This example is all about this concept.

Source code:

public class Example2 {

    public static void main(String argvs[]) {
        String s = String.join(null, "Java", "Tutorial", "Beginner");
        System.out.println(s);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException
	at java.util.Objects.requireNonNull(Objects.java:203)
	at java.lang.String.join(String.java:2451)
	at join.Example2.main(Example2.java:15)
C:\Users\Lenovo\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)

Example 3:

We can pass null as strings that will be joined with the delimiter. The program will treat the null strings normally, and it won’t generate any error.

Source code:

public class Example3 {

    public static void main(String argvs[]) {
        String s = String.join("/", "Java", "is", null, "of the", "best", " Programming languages ");
        System.out.println(s);
    }
}

Output:

run:
Java/is/null/of the/best/ Programming languages 
BUILD SUCCESSFUL (total time: 1 second)

References: