How can I check whether an array is null / empty?
To check if an array is null in Java, you can use the == operator and compare the array to null. For example:
To check if an array is null in Java, you can use the == operator and compare the array to null. For example:
int[] arr = null;
if (arr == null) {
System.out.println("Array is null");
}To check if an array is empty, you can use the length field of the array. An array is considered empty if its length is 0. For example:
int[] arr = new int[0];
if (arr.length == 0) {
System.out.println("Array is empty");
}Note that Java arrays do not have a built-in isEmpty() method like List or String classes. For production code, it's safer to combine both checks to avoid NullPointerException:
int[] arr = new int[0];
if (arr != null && arr.length > 0) {
System.out.println("Array is not null and not empty");
}I hope this helps! Let me know if you have any questions.