Library contents

Java String.join

Combine multiple pieces of text using a literal delimiter between adjacent elements.

A simple example

String.join

  1. Start with a and b, separator -
  2. Do this Join using the separator
  3. Result a-b
The separator goes between the two pieces exactly once.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(String.join("-", "a", "b"));
    }
}
Output
a-b

Syntax

Java syntax
public static String join(CharSequence delimiter, CharSequence... elements)
JDK 21 method signatures (2)
public static String join(CharSequence delimiter, CharSequence... elements)
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Print a shopping list on one line

A display receives an ordered list of items as separate values. Join them into one readable line with separators between neighboring values and no extra separator after the last one.

Resultrice, tea, oats
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(String.join(", ", "rice", "tea", "oats"));
    }
}
Output
rice, tea, oats

Two separators connect three items.

Advertisements

Build a route from its stops

A transport planner stores stops as separate names. Produce a route caption with a separator only between adjacent stops so the printed sign has no dangling punctuation.

ResultHome → Campus → Library
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        var stops = java.util.List.of("Home", "Campus", "Library");
        System.out.println(String.join(" → ", stops));
    }
}
Output
Home → Campus → Library

The same arrow is inserted between each pair of consecutive stops.

Build a parcel shelf identifier

The shelf prefix already includes the hyphen. Combine the two fragments in order without adding another separator. What label goes to the printer?

Given'North-' · '12'
Worked resultNorth-12

What to watch for

Join inserts separators only between elements. Decide how missing or null items should be represented first.

Documentation for String.join