Java.lang Package Classes

Java String - join() Method



The java.lang.String.join() method returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

Syntax

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

Parameters

delimiter Specify the delimiter that separates each element.
elements Specify the elements to join together.

Return Value

Returns a new String that is composed of the elements separated by the delimiter.

Exception

Throws NullPointerException, If delimiter or elements is null.

Example:

In the example below, join() method returns a new String containing CharSequence elements joined together with the specified delimiter.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String str1 = "Programming";
    String str2 = "is";
    String str3 = "fun";

    //joining all character sequence using
    //whitespace as delimiter
    String MyStr1 = String.join(" ", str1, str2, str3);
    System.out.println("MyStr1 is: " + MyStr1); 

    //joining all character sequence using
    //- as delimiter
    String MyStr2 = String.join("-", str1, str2, str3);
    System.out.println("MyStr2 is: " + MyStr2);
  }
}

The output of the above code will be:

MyStr1 is: Programming is fun
MyStr2 is: Programming-is-fun

❮ Java.lang - String