Course contentsShow
← Java
Lesson 2210 of 2,87043. String Handling in DepthFree lesson

String.join() Static Method: Concatenating with Delimiters

Use String.join() to combine strings or collections with a delimiter, the inverse operation of split().

String.join() Static Method: Concatenating with Delimiters

You'll learn how to use String.join() to efficiently combine strings with a delimiter—the exact opposite of what split() does.

What is String.join()?

String.join() is a static method that takes a delimiter and multiple strings (or a collection of strings) and weaves them together into a single string with the delimiter inserted between each element. Think of it as threading beads on a string: the delimiter is the thread, and your strings are the beads.

While split() breaks a string apart at delimiters, join() is the reverse—it assembles strings with delimiters.

Basic Syntax

String result = String.join(delimiter, element1, element2, ...);

Or with a collection:

String result = String.join(delimiter, collection);

Simple Examples

// Joining individual strings
String csv = String.join(", ", "Alice", "Bob", "Carol");
// Result: "Alice, Bob, Carol"

// Joining an array
String[] words = {"Java", "is", "awesome"};
String sentence = String.join(" ", words);
// Result: "Java is awesome"

// Recreating a path
String path = String.join("/", "home", "user", "documents");
// Result: "home/user/documents"

The Inverse of split()

Notice how join() perfectly reverses split():

String original = "apple,banana,cherry";
String[] parts = original.split(",");
String reconstructed = String.join(",", parts);
// reconstructed equals original

Handling Empty Strings

join() treats empty strings as valid elements:

String result = String.join("-", "a", "", "b");
// Result: "a--b"

Key Takeaway: String.join() is the inverse of split()—use it to efficiently concatenate strings or collections with a delimiter between elements, avoiding manual loops and StringBuilder complexity.