Java Tutorial Java Advanced Java References

Java String - join() Method



The Java 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)
public static String join(CharSequence delimiter, 
                          Iterable<? extends CharSequence> elements)

Parameters

delimiter Specify the delimiter that separates each element.
elements Specify the elements or an 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 CharSequence elements joined together with the specified delimiter.

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

Example:

In the example below, elements of an iterable (vector containing string elements) are joined together with specified delimiter.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    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 String Methods