Jakub Pomykała Jakub Pomykała - 1 month ago 7
Java Question

How to check if an element in a string array is empty?

How can I check if an element in a string array is empty? This is my example array:

private static String correct[] = new String[5];
static {
correct[1] = "some texT";
correct[2] = "some texT3";
correct[4] = "some texT2";
}


I can assign
null
to rest of elements, but I want to find another, better way to do this.
I found
isEmpty
, but it is available only on API 9 and above.

if(correct[0].length() > 0)

gives me a NPE.
if(correct[0] != null
also.

Answer

Have you tried the 'obvious':

if(correct[0] != null && correct[0].length() > 0) {
   //it is not null and it is not empty
}
Comments