Java.lang Package Classes

Java - String join() Method



The Java 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, 
                          Iterable<? extends CharSequence> elements)

Parameters

delimiter Specify the delimiter that separates each element.
elements Specify the Iterable containing 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 elements of an iterable (vector containing string elements) are joined together with specified delimiter.

import java.lang.*;
import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<String> MyVec = new Vector<String>();

    //populating vector
    MyVec.add("Programming");
    MyVec.add("is");
    MyVec.add("fun");

    //joining all elements of the vector
    //using whitespace as delimiter
    String MyStr1 = String.join(" ", MyVec);
    System.out.println("MyStr1 is: " + MyStr1); 

    //joining all elements of the vector 
    //using - as delimiter
    String MyStr2 = String.join("-", MyVec);
    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