Avatar of techbro
techbroFlag for United States of America

asked on 

Split() in Java

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!
Java

Avatar of undefined
Last Comment
techbro
Avatar of mrjoltcola
mrjoltcola
Flag of United States of America image

Well there is no space, so it is empty string.
ASKER CERTIFIED SOLUTION
Avatar of mrjoltcola
mrjoltcola
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of techbro
techbro
Flag of United States of America image

ASKER

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

Avatar of mrjoltcola
mrjoltcola
Flag of United States of America image

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
    ;

Avatar of techbro
techbro
Flag of United States of America image

ASKER

Thanks!
Java
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo