How to Check if an Array is Empty or Not in Java?
In Java, arrays do not have a built-in method like isEmpty()
to check if they are empty. So, we need to use other ways to check if an array is empty in Java.
Example: The simplest way to determine if an array is empty is by evaluating its length
or verifying if it is null
. This approach ensures our code handles both uninitialized and empty arrays effectively.
// Java program to Check if an Array is Empty
// by checking Array Length
public class ArrayCheck {
public static void main(String[] args) {
int[] arr = {};
// Check if the array is empty
if (arr == null || arr.length == 0) {
System.out.println("The array is empty.");
} else {
System.out.println("The array is not empty.");
}
}
}
Output
The array is empty.
Explanation: The
array == null
checks if the array reference is uninitialized or null
and the array.length == 0
checks if the array has no elements.
Other Methods to Check Empty Arrays
1. Using Utility Method
If we need to check arrays frequently, we can create a reusable utility method to simplify array emptiness check.
// Java Program to Check if an Array
// is Empty using a Utility Method
public class ArrayUtils {
public static boolean isArrayEmpty(int[] arr) {
return arr == null || arr.length == 0;
}
public static void main(String[] args) {
int[] arr = {}; // Example array
System.out.println("" + isArrayEmpty(arr));
}
}
Output
true
Note: This code is reusable and provides a clean, clear way to check if an array is empty in Java.
2. Using Java Optional
Java's Optional
class provides a clean and functional approach to check if an array is empty.
// Java Program to Check if an Array
// is Empty using Optional Class
import java.util.Optional;
public class ArrayCheck {
public static void main(String[] args) {
int[] arr = {}; // Example array
// Use Optional.ofNullable to
// handle null checks gracefully
boolean isEmpty = Optional.ofNullable(arr)
.map(arr1 -> arr1.length == 0)
.orElse(true);
System.out.println("" + isEmpty);
}
}
Output
true
Explanation: Here, we have used Optional.ofNullable
to safely handle potential null arrays, avoiding NullPointerException
. It checks if the array's length is 0
and prints true
if the array is empty or uninitialized.