Open In App

Java Array Empty Check

Last Updated : 09 Dec, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

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 is not 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.


Output
The array is not empty.

Other Methods to Check if an Array is Not Empty

1. Using a Utility Function

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.


Output
The array is not empty.

Explanation: The isArrayNotEmpty method checks both conditions (array != null and array.length > 0) and returns a boolean result.

2. Using Streams (Java 8+)

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).


Output
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.


Next Article
Practice Tags :

Similar Reads