Here is a set of test cases for you that demonstrate 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"); } } }
At startup, 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)
source share