If you're trying to check if a specific element in a specific position is empty (not only different from null, but from "" too), the presented solutions won't be enough.
Java has a lot of ways to do this. Let's see some of them:
You can convert your array into a List (using Arrays's asList method) and check the conditions through contains() method:
import java.util.*;
public class Test1 {
private static boolean method1_UsingArrays(String[] array) {
return Arrays.asList(array).contains(null)
|| Arrays.asList(array).contains("");
}
}
It's also possible to use Collections's disjoint method, to check whether two collections have elements in common or not:
import java.util.*;
public class Test2 {
private static String[] nullAndEmpty = {"", null};
private static boolean method2_UsingCollectionsDisjoint(String[] array) {
// disjoint returns true if the two specified collections have no elements in common.
return !Collections.disjoint( //
Arrays.asList(array), //
Arrays.asList(nullAndEmpty) //
);
}
}
If you're able to use Java 8 (my favorite option), it's possible to make use of the new Streams API.
import java.util.stream.*;
import java.util.*;
public class Test3 {
private static boolean method3_UsingJava8Streams(String[] array) {
return Stream.of(array).anyMatch(x -> x == null || "".equals(x));
}
}
Compared to the other options, this is even easier to handle in case you need to trim each of your strings (or call any of the other String's methods):
Stream.of(array).anyMatch(x -> x == null || "".equals(x.trim()));
Then, you can easily call and test them:
public static void main(String[] args) {
// Ok tests
String[] ok = {"a", "b", "c"};
System.out.println("Method 1 (Arrays - contains): " + method1_UsingArrays(ok)); // false
System.out.println("Method 2 (Disjoint): " + method2_UsingCollectionsDisjoint(ok)); // false
System.out.println("Method 3 (Java 8 Streams): " + method3_UsingJava8Streams(ok)); // false
System.out.println("-------------------------------");
// Nok tests
String[] nok = {"a", null, "c"};
System.out.println("Method 1 (Arrays - contains): " + method1_UsingArrays(nok)); // true
System.out.println("Method 2 (Disjoint): " + method2_UsingCollectionsDisjoint(nok)); // true
System.out.println("Method 3 (Java 8 Streams): " + method3_UsingJava8Streams(nok)); // true
// Nok tests
String[] nok2 = {"a", "", "c"};
System.out.println("Method 1 (Arrays - contains): " + method1_UsingArrays(nok2)); // true
System.out.println("Method 2 (Disjoint): " + method2_UsingCollectionsDisjoint(nok2)); // true
System.out.println("Method 3 (Java 8 Streams): " + method3_UsingJava8Streams(nok2)); // true
}