How to check whether the array is empty and null?

In Java, checking whether an array is empty or null involves two separate conditions:

✅ 1. Check for null:

This means the array variable hasn’t been initialized.

if (arr == null) {
System.out.println(“Array is null”);
}

✅ 2. Check if the array is empty:

This means the array exists, but has a length of zero—no elements inside.

if (arr != null && arr.length == 0) {
System.out.println(“Array is empty”);
}

Explanation:

  • array == null checks if the reference points to nothing.
  • array.length == 0 checks if the array has no elements.

This simple condition ensures your code handles both cases safely. Let me know if you’re working with a specific type of array—like int[] or String[]—and I can show tailored examples too.

Leave a Reply

Your email address will not be published. Required fields are marked *