C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The second and further arguments to join() are the Strings we want to combine together.
Delimiter: The delimiter (or separator value) is three periods here. This can be any character or string.
Result: String.join returns a new String. It contains the merged-together data. No trailing delimiter is added.
Java program that uses String.join method
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);
}
}
Output
bird...cat...wildebeest
Here: We pass the delimiter (a comma) and three values (value1, value2 and value3). Join handles these just like an array.
Java program that joins individual string values
public class Program {
public static void main(String[] args) {
String value1 = "dot";
String value2 = "net";
String value3 = "Codex";
// Join the three local variables' data.
String joined = String.join(",", value1, value2, value3);
System.out.println(joined);
}
}
Output
dot,net,Codex
Java program that uses empty delimiter
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);
}
}
Output
ABC
Version 1: This version of the code uses separate string arguments to the String.join method.
Version 2: This code uses an array argument to String.join instead of multiple separate arguments.
Result: This benchmark shows that passing an array to String.join is faster than passing separate strings.
Java program that times String.join argument passing
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);
}
}
Output
1104 ms: 3 Strings
934 ms: String array