Explain Codes LogoExplain Codes Logo

How can I check whether an array is null / empty?

java
array-null-check
java-arrays
best-practices
Anton ShumikhinbyAnton Shumikhin·Aug 27, 2024
TLDR
if (array != null && array.length > 0) { // Array exists and isn't a loner }

This sanity check ensures that your array is not null and its length is greater than 0, hence ready for action.

Nitty-gritty: Understanding arrays

Let's dive into what arrays in Java really are and the states that they can exist in.

Initialized, empty or null: Know your array

An array in Java can be initialized with values, empty, or null. It's important to note that a null array isn't empty; it's a ghost array, it has never been born!

Null vs empty: The tale of two states

An array == null situation indicates a phantom array — oh, it doesn't exist! Whereas, an empty array is a house well built but devoid of any furniture — it exists, but it's vacant.

if (array == null) {
    System.out.println("Ghost array spotted!");   // No memory allocation
} else if (array.length == 0) {
    System.out.println("Empty house... cricket noises.");  // Memory allocated but no elements
}

The curious case of null elements

An array may be populated with nulls. For such arrays, emptiness is a matter of perspective. Think of it like a house filled with air — technically not empty, but practically?

boolean isTrulyEmpty = true; if (array != null) { for (Object item : array) { if (item != null) { isTrulyEmpty = false; break; } } }

This array is a pseudo-ghost, appearing empty but not quite there!

Fellow coder, meet Apache Commons Lang

The ArrayUtils class from Apache Commons Lang library is your best bud in your array adventures:

if (ArrayUtils.isEmpty(array)) { System.out.println("Ghost or barren, safe for the ninja code!"); // Covers both null and empty arrays }

Embrace Java 8+: Using streams

If you're blessed with Java 8 or higher, streams can slay the emptiness dragon in style!

boolean isNonGhostNorEmpty = array != null && Arrays.stream(array).allMatch(Objects::nonNull);

The above line combines the powers of Arrays.stream() and Objects::nonNull to ensure that your array isn't a ghost or a barren land.