String.split method incompatibility in Java 8 and Java 7

This is a note about the problem that I encountered in the process of translating the project from Java 7 to Java 8. It happened about six months ago, but decided to write now because I suddenly remembered about it (the problem).

So, right off the bat.

Here is the result of executing the code:
package test;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        System.out.println("result: " + Arrays.toString("0000".split("")));
    }
}

under Java 8:
result: [0, 0, 0, 0]

and Java 7:
result: [, 0, 0, 0, 0]


As you can see, the string splits in different ways, and because of this problem, I caught an ArrayIndexOutOfBoundsException .
It was unpleasant, but I was able to survive, gathered all my will into a fist and decided to figure out what the problem was.
Here is what the official documentation writes :
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

Those. now in a situation where the string is split by an empty character, a zero empty element is not generated.
This behavior is more logical than the old one, but the compatibility failure was a surprise to me. In any case, nothing can be done, so I wish you to be careful and catch as few problems as possible :).

PS Later, I found a discussion of this problem on stackoverflow.com.
PPS As Borz user correctly pointed out, it was a bug . Apparently you need to read better changelogs.

Also popular now: