How can I check whether an array is null / empty?
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?
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:
Embrace Java 8+: Using streams
If you're blessed with Java 8 or higher, streams can slay the emptiness dragon in style!
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.
Was this article helpful?