How do split and String.join work in Java, and what are the subtle differences in how they treat the separator?
The two of them do opposite jobs. The method split cuts one string into many, and the method join joins many into one.
The method split takes a separator and gives you an array of pieces. The method join takes a separator and a list of pieces, and it gives you one string back.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println("join : " + String.join(", ", "a", "b", "c"));
System.out.println("join a list : " + String.join(", ", Arrays.asList("a", "b", "c")));
String[] pieces = "a,b,c".split(",");
System.out.println("split : " + Arrays.toString(pieces));
// Trailing empty pieces are dropped by split.
String[] trailing = "a,b,,".split(",");
System.out.println("split trailing : " + Arrays.toString(trailing));
// Limit the number of pieces with a negative limit.
String[] limited = "a,b,c,d".split(",", -1);
System.out.println("split limit : " + Arrays.toString(limited));
}
}
There are two differences that surprise people, and they both come from the fact that the separator is treated differently by the two methods.
The first one is the separator itself. The method join takes the separator as plain text, so you write String.join(", ", ...) and you get exactly those characters between the pieces. The method split takes the separator as a regular expression, so a full stop in it means "any character at all" and you have to write split("\\.") when you mean a real full stop.
The second one is the empty pieces at the end. The method split throws away the empty pieces that come after the last separator, so "a,b,,".split(",") gives you two pieces and not four. If you want to keep them, you pass a negative limit, and then the count comes out as you would expect.
So the rule to remember is this. The separator of join is plain text, the separator of split is a pattern, and split quietly drops the empty pieces at the end unless you tell it not to.
The next question in this topic compares split with the older class that does the same job.