Facebook Page Twitter Page LinkedIn Page
× Java Tutorial Java Advanced Java Resources


The Java string join() method is used to return 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 below example, join() method to used to return 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 below example, 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