how to check for an empty array java

I would consider using ArrayUtils.is empty by adding Apache Commons Lang from here http://commons.apache.org/proper/commons-lang/download_lang.cgi

The big advantage is this will null check the array for you in a clean and easily readible way.

You can then do:

if (ArrayUtils.isEmpty(arrayName) {
    System.out.printLn("Array empty");
} else {
    System.out.printLn("Array not empty");
}

As poited out in the other answers, the length property of Array will give the length of the array. But it is always recommended to check if the array is null before doing any operation on it or else it will throw NullPointerException if the array is null.

     if (array != null) {
            if (array.length == 0)
                System.out.println("Empty Array Size=0");
            else
                System.out.println("Array Not Empty -  Size = " + array.length);

        } else
            System.out.println("array is null");
    } 

In array class we have a static variable defined "length", which holds the number of elements in array object. You can use that to find the length as:

if(arrayName.length == 0)
  System.out.println("array empty");
else 
  System.out.println("array not empty");

Tags:

Java

Arrays