Behaviour of Java String.split() when some answers are the empty string

May 23, 2013 [Java, Programming, Tech]

Can you guess the output of this program?

class SplitTest
{
    static void split( String s )
    {
        System.out.println( s.split( ";" ).length );
    }

    public static void main( String[] args )
    {
        split("");
        split(";");
        split("x;");
        split(";y");
    }
}

Here it is:

$ javac SplitTest.java && java SplitTest
1
0
1
2

Wow. Docs: String.split.

Side note: It's not easy to fit Java examples into tweets.

class X{static void x(String s){System.out.println(s.split(";").length);}public static void main(String[]a){x("");x(";");x("x;");x(";y");}}

— Andy Balaam (@andybalaam) May 23, 2013