Home » Java » is it always safe to use the first element of the array returned by split?

is it always safe to use the first element of the array returned by split?

Posted by: admin December 28, 2021 Leave a comment

Questions:

I’m pretty sure the answer is yes, but I just want to confirm that there is never a situation where a non null string (regardless of what it contains) would return anything but a valid String as the first member of the array returned by split.

In other words.

String foo = ""; // or "something" or "a b c" or any valid string at all

String[] bar = foo.split(",")[0];

My understanding is that bar will never be null and the assignment line has no way to fail. If the delimiter is not found in the string it just returns foo in its entirety as the first element of the returned array.

Answers:

No,, It may fail

It would fail to ArrayIndexOutOfBound if the foo =","

###

Yes. bar will be equal to the string “”

.split(“,”) attempts to split after the comma, but there is no comma in the original string,
so the original string will get returned.

What would be trickier is:

String s = ",,,,,,,"

String[] sarray = s.split(",");

Here sarray[0] will return ArrayIndexOutOfBoundsException.

###

(1) If foo is a direct match for the regex pattern, the array returned from split has length 0 and foo.split[0] will throw an ArrayIndexOutOfBoundsException.

(2) Keep in mind String.split may throw a PatternSyntaxException if the regex is invalid at runtime.

###

Here’s a set of test cases for you that demonstrate the above:

public class Test {
    public static void main(String[] args){
        test("x,y");
        test(",y");
        test("");
        test(",");
    }

    private static void test(String x){
        System.out.println("testing split on value ["+x+"]");
        String y = x.split(",")[0];
        if(null == y){
            System.out.println("x returned a null value for first array element");
        } else if(y.length() < 1) {
            System.out.println("x returned an empty string for first array element");
        } else {
            System.out.println("x returned a value for first array element");
        }
    }
}

When run, this is what you get:

$ javac Test.java && java Test
testing split on value [x,y]
x returned a value for first array element
testing split on value [,y]
x returned an empty string for first array element
testing split on value []
x returned an empty string for first array element
testing split on value [,]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at Test.test(Test.java:11)
        at Test.main(Test.java:6)