String split method behavior

java, split, string

Solution

From the documentation:

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.

To answer your question, it does what it is expected to do: the returned substring is terminated by the end of the input string (as there was no `,` to be found). The documentation also states:

If the expression does not match any part of the input then the resulting array has just one element, namely this string.

Note that this is a consequence of the first statement. It is not an additional circumstance that the Java developers added in case the search string could not be found.

Problem

I don't see why does the following output makes sense. String split method on an empty String returning an array of String with length 1 `String[] split = "".split(",");` `System.out.println(split.length);` Returns array of String with length 1 `String[] split = "Java".split(",");` `System.out.println(split.length);` Returns array of String with length 1 How to differentiate??

Original source