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
NullPointerException if element or delimiter is null.
Java String join() Method Example
FileName: StringJoinExample.javaTest 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.
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(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.
/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.
null- wake up - eat - write content for JTP - eat - sleep