Join
In a program, Strings are often separate. They are elements in an array, or just String
variables in a method. With join()
we merge them.
In Java, the join method receives a variable number of arguments. It accepts first a delimiter string
—characters that are inserted between all joined strings.
join()
are the Strings we want to combine together.First, we call the String.join
static
method with an array of three Strings. The values array is passed as the second argument to join.
string
.String.join
returns a new String
. It contains the merged-together data. No trailing delimiter is added.public class Program { public static void main(String[] args) { // Create String array of three elements. String[] values = { "bird", "cat", "wildebeest" }; // Join the elements together. String result = String.join("...", values); System.out.println(result); } }bird...cat...wildebeest
string
argumentsString.join
is versatile. We don't need to pass it an array of Strings—it can make its own array from separate arguments.
Join
handles these just like an array.public class Program { public static void main(String[] args) { String value1 = "dot"; String value2 = "net"; String value3 = "perls"; // Join the three local variables data. String joined = String.join(",", value1, value2, value3); System.out.println(joined); } }dot,net,perls
We can use an empty delimiter string
. This is a way to concatenate all the strings together with nothing separating them.
public class Program { public static void main(String[] args) { String[] array = { "A", "B", "C" }; // Join with an empty delimiter. String merged = String.join("", array); System.out.println(merged); } }ABC
In some programs, we have a choice in how to call String.join
—we can change code to use an array or avoid arrays. String.join
can handle either case.
string
arguments to the String.join
method.String.join
instead of multiple separate arguments.String.join
is faster than passing separate strings.public class Program { public static void main(String[] args) { String value1 = "cat"; String value2 = "dog"; String value3 = "elephant"; String[] array = new String[3]; array[0] = "cat"; array[1] = "dog"; array[2] = "elephant"; long t1 = System.currentTimeMillis(); // Version 1: pass separate string arguments. for (int i = 0; i < 10000000; i++) { String result = String.join(":", value1, value2, value3); if (result.length() == 0) { System.out.println(0); } } long t2 = System.currentTimeMillis(); // Version 2: pass array of Strings. for (int i = 0; i < 10000000; i++) { String result = String.join(":", array); if (result.length() == 0) { System.out.println(0); } } long t3 = System.currentTimeMillis(); // ... Result times. System.out.println(t2 - t1); System.out.println(t3 - t2); } }1104 ms: 3 Strings 934 ms: String array
Join
is a good way to combine strings. With it, we can create CSV (comma-separate values) files. Joined strings can be parsed with split.