java – How can I check whether an array is null / empty?

java – How can I check whether an array is null / empty?

Theres a key difference between a null array and an empty array. This is a test for null.

int arr[] = null;
if (arr == null) {
  System.out.println(array is null);
}

Empty here has no official meaning. Im choosing to define empty as having 0 elements:

arr = new int[0];
if (arr.length == 0) {
  System.out.println(array is empty);
}

An alternative definition of empty is if all the elements are null:

Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
  if (arr[i] != null) {
    empty = false;
    break;
  }
}

or

Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
  if (ob != null) {
    empty = false;
    break;
  }
}

ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty

java – How can I check whether an array is null / empty?

Look at its length:

int[] i = ...;
if (i.length == 0) { } // no elements in the array

Though its safer to check for null at the same time:

if (i == null || i.length == 0) { }

Leave a Reply

Your email address will not be published.