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:
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");
}
You can also use the isEmpty
method of the java.util.Arrays
class to check if an array is empty:
import java.util.Arrays;
int[] arr = new int[0];
if (Arrays.isEmpty(arr)) {
System.out.println("Array is empty");
}
I hope this helps! Let me know if you have any questions.