Java’s String.join() method combines multiple character sequences into one string, placing a delimiter between adjacent values. For example, String.join(", ", "red", "green", "blue") returns red, green, blue. It has overloads for a sequence of values and for an Iterable, making it a straightforward choice for joining arrays and collections.
What String.join does
String.join() is a static method on Java’s String class. It takes a delimiter and a group of values, then returns a new string with the delimiter inserted between each pair of values. The delimiter is not added before the first value or after the last one.
The method was introduced in Java 8. Its two forms are:
String.join(CharSequence delimiter, CharSequence... elements)
String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
A CharSequence is a general interface for character data. String implements it, as do types such as StringBuilder. In ordinary use, you will most often pass strings. Because the first overload is a varargs method, you can provide the values as separate arguments or pass a compatible array. The second form accepts collections such as a List<String>.
The result is always a String; the method does not change the input array or collection. Since String is in java.lang, no import is needed to call it. The key decision is usually choosing a delimiter that suits the output, such as a comma and space for a readable list or a newline for separate lines.
Basic syntax and examples
Pass the delimiter first, followed by the values to join. The delimiter may contain one character, several characters, or no characters at all.
String colors = String.join(" | ", "red", "green", "blue");
// colors is "red | green | blue"
String path = String.join("/", "home", "sam", "notes");
// path is "home/sam/notes"
String combined = String.join("", "sun", "flower");
// combined is "sunflower"
For a collection, use the Iterable overload. Here, Arrays.asList is used so the example works in Java 8:
List<String> languages = Arrays.asList("Java", "Kotlin", "Scala");
String result = String.join(", ", languages);
// result is "Java, Kotlin, Scala"
These examples assume the relevant types are imported, such as java.util.List and java.util.Arrays. You can also pass a String[] directly because the varargs parameter accepts an array:
String[] codes = {"A1", "B2", "C3"};
String result = String.join("-", codes);
// result is "A1-B2-C3"
The values are joined in the order supplied. For a list, that means its iteration order; if the collection’s order is unspecified, the resulting order may be unspecified too. Sort the values first if the output needs a predictable order.
Joining collections and stream results
String.join() accepts an Iterable, so it works directly with common collection types including lists and sets. It does not accept a Java Stream directly: a stream is not an Iterable. For a stream pipeline, use Collectors.joining(), which is also available from Java 8.
String result = names.stream()
.filter(name -> !name.isBlank())
.collect(Collectors.joining(", "));
This example filters out blank names before joining the remaining values. The stream form is useful when values need to be filtered or transformed as part of the same operation. For instance, a map step can turn numbers into formatted labels before collection. Remember that String.isBlank() itself requires Java 11; on Java 8, use an appropriate alternative such as checking whether trim() is empty, while keeping in mind that trim() has different whitespace rules.
If no stream processing is needed, converting a collection into a stream just to join it adds unnecessary steps. Use String.join(delimiter, collection) for an existing iterable, and reserve Collectors.joining() for a stream pipeline or when its prefix-and-suffix options are useful.
Empty values, nulls, and delimiters
Several edge cases affect the returned text. An empty collection produces an empty string, because there are no values or separators to append. A single value is returned without a delimiter. With multiple values, the delimiter appears exactly between them.
- An empty delimiter concatenates values with nothing between them.
- An empty string used as an element is still an element, even though it contributes no visible characters.
- A null element is represented by the four characters
null. - A null delimiter causes a
NullPointerException. - A null array or null iterable also causes a
NullPointerException.
For example, joining ["oak", "", "pine"] with ", " produces oak, , pine. That is not the same as removing the empty element: the separators still reflect its position. Similarly, joining ["oak", null, "pine"] produces oak, null, pine. This behavior can be surprising if the output is intended for a user or another system.
If nulls should be omitted, filter them out before joining. If they should have a custom label, map them to that label first. Do not confuse a null element with a null collection: a null element is rendered as text, but a null input container cannot be traversed and results in an exception.
Choosing between String.join and alternatives
For a fixed set of values or an existing collection, String.join() is usually the clearest option. Other Java tools are useful when the formatting or construction process has extra requirements.
- Use
String.join()when the goal is simply to put a delimiter between known values or an iterable’s elements. - Use
Collectors.joining()when values come from a stream, need filtering or mapping, or need a prefix and suffix. Its overload can take a delimiter, prefix, and suffix. - Use
StringJoinerwhen values will be added gradually and you want delimiter, prefix, and suffix handling in a dedicated object. - Use
StringBuilderwhen constructing output in a loop with conditional formatting or other custom logic.
For example, Collectors.joining(", ", "[", "]") can produce [Java, Kotlin] from a stream. A StringJoiner offers similar formatting when adding values one at a time. For a simple collection, manually appending each value to a builder means you must also track whether it is the first item so that you do not accidentally add a leading or trailing delimiter.
These choices are about clarity and requirements, not a universal speed ranking. For most everyday joining tasks, prefer the concise method that expresses the intended operation. If a performance-sensitive path is involved, benchmark the actual workload rather than assuming one approach is always faster.
Common mistakes and practical limitations
A common mistake is expecting the delimiter to be added at the end. It is only placed between elements, so joining three values with a comma produces two commas, not three. If a trailing separator is genuinely required by a format, add it deliberately or use a more suitable formatter rather than relying on a joining method to provide one.
Another misconception is that joining creates valid CSV or safely escaped output. String.join() only concatenates text; it does not quote fields containing commas, escape quotation marks, encode special characters, or validate a path or command. For example, joining two fields with commas will not protect a field that itself contains a comma. Use a CSV library for CSV data and the relevant escaping or encoding rules for other structured formats.
Also check the inputs’ order and content before joining. A set may not provide the order a display requires, and whitespace in an element is preserved. A string such as " Java " remains padded after joining. Trim, sort, filter, or format values explicitly when the desired result calls for it.
Version and compatibility notes
String.join() has been part of the Java standard library since Java 8, as have StringJoiner and Collectors.joining(). It is therefore available in Java 8 and later, but not in Java 7 or earlier. When maintaining older code, check the project’s configured Java source and target versions as well as the installed runtime; an IDE may support newer language features while the deployed application still targets an older Java release.
Java version differences can matter in examples surrounding the method. The collection example using Arrays.asList is compatible with Java 8. The stream collector is also Java 8-compatible, but newer convenience methods used in a stream pipeline may have later minimum versions. For example, String.isBlank() arrived in Java 11. Keep the join operation and nearby helper methods’ compatibility requirements separate when adapting code.
Frequently Asked Questions
Is String.join available in Java 8?
Yes. String.join() was introduced in Java 8. It has overloads for varargs character sequences and for an Iterable.
Does String.join add a delimiter at the end?
No. It puts the delimiter only between adjacent elements. If you join an empty list, the result is empty; if you join one element, there is no delimiter in the result.
Can String.join join a List?
Yes. A list of strings is an Iterable, so you can pass it directly as the second argument: String.join(", ", names).
What happens if an element is null?
A null element is added as the text null. A null delimiter or a null array or iterable input instead causes a NullPointerException.
Can String.join take a Stream?
No. A stream is not an Iterable, so it does not match either overload. Use stream.collect(Collectors.joining(delimiter)) to join values from a stream.
Related
- Databricks SQL CONTAINS: Find Text in a String
- Split Syntax in Java: Examples and Common Pitfalls
- JavaScript String split(): Syntax, Examples, and Tips
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- F Statistic in Excel: How to Find ItTo find an F-statistic in Excel, arrange your data in columns, enable the Analysis ToolPak if needed, then…
- Excel Custom Number Format: How to Create and Apply ItTo set a custom number format in Excel for Microsoft 365 on Windows, select the cells, press Ctrl+1,…
- CATIA Drafting: How to Split a LineIn CATIA Drafting, use the Split command in the 2D geometry tools: start the command, select the line…
- JavaScript String Split to Array: Examples and TipsUse JavaScript’s String.prototype.split() method to turn a string into an array: call it on the string and provide…
- Excel Format Cells Shortcut: Open the Dialog in SecondsIn Excel for Windows, select a cell or range and press Ctrl+1 to open the Format Cells dialog…
- Merge Cells Horizontally in Google Sheets: Steps and TipsTo merge cells horizontally in Google Sheets, select the cells you want to combine, then choose Format >…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.