English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java String join() usage and example

Java String (String) Methods

The Java String join() method returns a new string that has the specified elements and delimiter.

Syntax of the string join() method:

String.join(CharSequence delimiter, Iterable elements)

or

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

Here, ... indicates that one or more CharSequence (character sequences) can be present.
Note: join() is a static method. You do not need to create a string object to call this method. Instead, we use the class name String to call this method.

join() parameters

  • delimiter - Delimiter used to connect elements

  • elements - Elements to be connected

join() return value

  • Returns a string

Example1Java String join() and 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 passed three strings Java, is, and fun to the join() method. These strings are connected using-connected using delimiters.

Example2: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, we will create an ArrayList of String type. The elements of the ArrayList use-connected using delimiters.

Java String (String) Methods