Split() in Java

techbro
techbro used Ask the Experts™
on
When I try this code below, a String array containing 3 elements is returned. But if you take a look at the code, there are two more semicolons in the end.

My question is, why 3 elements is returned instead of 4 elements since the space could also be counted and stored in the String array?

"name:john;;sex:m;;".split(";");

Open in new window


I will appreciate your response!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2009

Commented:
Well there is no space, so it is empty string.
Top Expert 2009
Commented:
From docs http://download.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)

"Trailing empty strings are therefore not included in the resulting array. "

Author

Commented:
mrjoltcola, thank you for your response.
One more thing I need to know. Are the "empty string" and NULL similar to each other?

Top Expert 2009

Commented:
Not in Java. An empty string is a valid string object of 0 length (""). null is the complete absence of a string object.

So the difference is it is legal to use an empty string as a string object, to test it, call methods on it:

string empty = "";
string sNull = null;

if(empty[0] == 'A')  // legal, will execute (but will eval to false)
    ;  

if(sNull[0] == 'A') // will throw null pointer exceptin
    ;

Author

Commented:
Thanks!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial