Java String join()

The join() method returns a new string with the given elements joined with the specified delimiter.

Example

class Main {
  public static void main(String[] args) {
    String str1 = "I";
    String str2 = "love";
    String str3 = "Java";

// join strings with space between them String joinedStr = String.join(" ", str1, str2, str3);
System.out.println(joinedStr); } } // Output: I love Java

Syntax of join()

The syntax of the string join() method is either:

String.join(CharSequence delimiter, 
            Iterable elements)

or

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

Here, ... signifies there can be one or more CharSequence.

Note: join() is a static method. You do not need to create a string object to call this method. Rather, we call the method using the class name String.


join() Parameters

The join() method takes two parameters.

  • delimiter - the delimiter to be joined with the elements
  • elements - elements to be joined

Notes:

  • You can pass any class that implements CharSequence to join().
  • If an iterable is passed, its elements will be joined. The iterable must implement CharSequence.
  • String, StringBuffer, CharBuffer etc. are CharSequence as these classes implement it.

join() Return Value

  • returns a string

Example 1: Java String join() With CharSequence()

class Main {
  public static void main(String[] args) {
    String result;

result = String.join("-", "Java", "is", "fun");
System.out.println(result); // Java-is-fun } }

Here, we have passed three strings Java, is and fun to the join() method. These strings are joined using the - delimiter.


Example 2: Java String join() With Iterable

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList<String> text = new ArrayList<>();

    // adding elements to the arraylist
    text.add("Java");
    text.add("is");
    text.add("fun");

    String result;

result = String.join("-", text);
System.out.println(result); // Java-is-fun } }

Here, an ArrayList of String type is created. The elements of array list are joined using the - delimiter.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges