Java String join()

The Java String class join() method returns a string joined with a given delimiter. In the String join() method, the delimiter is copied for each element. The join() method is included in the Java string since JDK 1.8.

There are two types of join() methods in the Java String class.

Signature

The signature or syntax of the join() method is given below:

Parameters

delimiter : char value to be added with each element

elements : char value to be attached with delimiter

Returns

joined string with delimiter

Exception Throws

NullPointerException if element or delimiter is null.

Since

1.8

Internal Implementation

Java String join() Method Example

FileName: StringJoinExample.java

Test it Now

Output:

welcome-to-javatpoint

Java String join() Method Example 2

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

FileName: StringJoinExample2.java

Output:

25/06/2018 12:10:10

Java String join() Method Example 3

In the case of using null as a delimiter, we get the null pointer exception. The following example confirms the same.

FileName: StringJoinExample3.java

Output:

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.lang.String.join(String.java:2393)
	at StringJoinExample3.main(StringJoinExample3.java:7)

However, if the elements that have to be attached with the delimiter are null then, we get the ambiguity. It is because there are two join() methods, and null is acceptable for both types of the join() method. Observe the following example.

FileName: StringJoinExample4.java

Output:

/StringJoinExample4.java:7: error: reference to join is ambiguous
str = String.join("India", null);
            ^
  both method join(CharSequence,CharSequence...) in String and method join(CharSequence,Iterable<? extends CharSequence>) in String match
/StringJoinExample4.java:7: warning: non-varargs call of varargs method with inexact argument type for last parameter;
str = String.join("India", null);
                           ^
  cast to CharSequence for a varargs call
  cast to CharSequence[] for a non-varargs call and to suppress this warning
1 error
1 warning

Java String join() Method Example 4

If the elements that have to be attached with the delimiter have some strings, in which a few of them are null, then the null elements are treated as a normal string, and we do not get any exception or error. Let's understand it through an example.

FileName: StringJoinExample5.java

Output:

null- wake up - eat - write content for JTP - eat - sleep





Latest Courses