What is the output of below?

String foo = "foo bar moo";
String[] ar = foo.split("\\s+");
System.out.println(ar.length);

3 as expected.

What is the output of below?

String foo = "foo bar moo                  ";
String[] ar = foo.split("\\s+");
System.out.println(ar.length);

3 as expected.

What is the output of below?

String foo = "                 foo bar moo";
String[] ar = foo.split("\\s+");
System.out.println(ar.length);

3 as expected?
Nope. It is 4 now.

Why?
Below is what the api says regarding the split method.

Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Advertisements