![]() |
VOOZH | about |
In Java, an array is considered non-empty, if it is not null and its length is greater than 0. It is important to check if an array isnot empty before performing operations on it to avoid NullPointerException or unnecessary processing.
Example: The simplest way to check if an array is not empty is by verifying that the array is not null and the array length is greater than zero.
The array is not empty.
For a reusable solution, we can encapsulate the null and length checks in a utility function. This makes the code cleaner and reusable across multiple scenarios.
The array is not empty.
Explanation: The isArrayNotEmpty method checks both conditions (array != null and array.length > 0) and returns a boolean result.
Java 8 introduced streams, which can also be used to check if an array contains elements. While this method is more complex for basic checks, it is useful when we want to extend the logic (e.g., filtering elements).
The array is not empty.
Explanation: The Arrays.stream(array) converts the array into a stream and the .findAny().isPresent() checks if any element is present in the stream.