Java String join() Method Example Tutorial
Java String join() is an inbuilt method that is used to join character sequences with a specific delimiter. The delimiter is added between each different character sequence to combine all the character sequences into a single String. If you want to convert array to string, then Java String join() method is useful.
Java String join()
Java string join() method returns a string joined with the given delimiter. In the string join method, the delimiter is copied for each element.
In the case of a null element, “null” is added.
See the following figure.
See the following syntax.
public static String join(CharSequence delimiter, CharSequence... elements) or public static String join(CharSequence delimiter, Iterable<? Extends CharSequence> elements)
Parameters:
delimiter: This is what the character sequences are joined with each other.
elements: The character sequences in question. This can also be entered utilizing the Collections framework extending Iterable.
Returns:
The concatenated String.
Throws:
NullPointerException if the delimiter is null. However, if the character sequence is null, the String “null” is added in place of it.
See the following code example.
public class Example1 { public static void main(String[] args) { String s1 = String.join("+", "One", "One"); System.out.println(s1); } }
Output
Let’s see an example two.
public class Example2 { public static void main(String[] args) { String s1 = String.join(null, "One", "One"); System.out.println(s1); } }
Output
In the above example, we got the output NullPointerException.
Let’s see the third example.
public class Example3 { public static void main(String[] args) { String s1 = String.join("+", null, "One"); System.out.println(s1); } }
Output
See the next example.
public class Example4 { public static void main(String[] args) { String s1 = null; String s2 = String.join("+", s1, "One"); System.out.println(s2); } }
Output
The following example demonstrates syntax of the form public static String join(CharSequence delimiter, Iterable<? Extends CharSequence> elements) with the use of an ArrayList.
See the following code.
import java.util.*; public class Example5 { public static void main(String[] args) { ArrayList<String> arrlst = new ArrayList<>(); arrlst.add("One"); arrlst.add("Two"); arrlst.add("Three"); arrlst.add("Four"); arrlst.add("Five"); String s1 = String.join("+", arrlst); System.out.println(s1); } }
Output
Finally, Java String join() Method Example is over.