Javatpoint Logo
Javatpoint Logo

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.


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


delimiter : char value to be added with each element

elements : char value to be attached with delimiter


joined string with delimiter

Exception Throws

NullPointerException if element or delimiter is null.



Internal Implementation

Java String join() Method Example


Test it Now



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.



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.



Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(
	at java.base/java.lang.String.join(
	at StringJoinExample3.main(

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.



/ 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
/ 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.



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

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA