Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify if a string.split() returns null

I am reading data from a file:

Some Name;1|IN03PLF;IN02SDI;IN03MAP;IN02SDA;IN01ARC
Some Other Name;2|IN01ALG;IN01ANZ
Another Name;3|
Test Testson;4|IN03MAP;IN01ARC;IN01ALG

I use string.split() for every line I read from that file, like this:

String args[]         = line.split("\\|");                  
String candidatArgs[] = args[0].split(";");

if (args[1] != "" || args[1] != null) { 

    String inscrieriString[] = args[1].split(";");

Thing is: when I reach Another Name;3| after .split("\\|") the second part (args[1]) should be empty, either null or "" (I don't really know).

However I get an Array index out of bounds error on if (args[1] != "" || args[1] != null) (again, at: Another Name;3|)

like image 528
Kalec Avatar asked Feb 13 '13 13:02

Kalec


People also ask

Can split return null?

split(CharSequence input, int limit) . The return value comes from a non-null ArrayList on which toArray is called. toArray does not return null: in the event of an empty list you'll get an empty array back. So in the end, no, you don't have to check for null.

Why does split return empty string?

The natural consequence is that if the string does not contain the delimiter, a singleton array containing just the input string is returned, Second, remove all the rightmost empty strings. This is the reason ",,,". split(",") returns empty array.

How do you check if a string is null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

Can we check string == null?

We can simply compare the string with Null using == relational operator. Print true if the above condition is true. Else print false.


2 Answers

The args will only have one element in it.

if (args.length > 1) {
    String inscrieriString[] = args[1].split(";");
}
like image 133
David Lavender Avatar answered Sep 29 '22 14:09

David Lavender


You need to check the length of your args array.

String.split() returns an array of length 1 for your third line, so that args[1] is out of bounds. You should also use String.isEmpty() instead of != "".

Most likely, you can even skip your additional checks - checking the array length should be sufficient:

if (args.length > 1) {
    String inscrieriString[] = args[1].split(";");
    ...
}
like image 43
Andreas Fester Avatar answered Sep 29 '22 13:09

Andreas Fester