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

JavaArrays

Java Problem Overview


I have an int array which has no elements and I'm trying to check whether it's empty.

For example, why is the condition of the if-statement in the code below never true?

int[] k = new int[3];

if (k == null) {
    System.out.println(k.length);
}

Java Solutions


Solution 1 - Java

There's 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. I'm 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;
  }
}

Solution 2 - Java

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

Solution 3 - Java

Look at its length:

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

Though it's safer to check for null at the same time:

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

Solution 4 - Java

Method to check array for null or empty also is present on org.apache.commons.lang:

import org.apache.commons.lang.ArrayUtils;

ArrayUtils.isEmpty(array);

Solution 5 - Java

I am from .net background. However, java/c# are more/less same.

If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.

It will be null, when you don't new it up.
e.g.

int[] numbers = null; // changed as per @Joachim's suggestion.
if (numbers == null)
{
   System.out.println("yes, it is null. Please new it up");
}

Solution 6 - Java

An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.

Solution 7 - Java

In Java 8+ you achieve this with the help of streams allMatch method.

For primitive:

int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)

For Object:

Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)

Solution 8 - Java

The point here very simply is that the variable k isn't null because it points to the array. It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything.

Solution 9 - Java

I tested as below. Hope it helps.

Integer[] integers1 = new Integer[10];
        System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
        for (Integer integer : integers1) {
            System.out.println(integer); //prints all 0s
        }

//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
//        integers1[2] = 0;
        for (Integer integer : integers1) {
            System.out.println(integer); //Still it prints all 0s but it is not empty
            //but that manually added 0 is different
        }

//Even we manually add 0, still we need to treat it as null. This is semantic logic.

        Integer[] integers2 = new Integer[20];
        integers2 = null; //array is nullified
//        integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line. 
        if (integers2 == null) {
            System.out.println("null Array");
        }   

Solution 10 - Java

if you are trying to check that in spring framework then isEmpty(Object[]) method in ObjectUtils class helps,

public static boolean isEmpty(@Nullable Object[] array) {
		return (array == null || array.length == 0);
	}

Solution 11 - Java

An int array without elements is not necessarily null. It will only be null if it hasn't been allocated yet. See this tutorial for more information about Java arrays.

You can test the array's length:

void foo(int[] data)
{
  if(data.length == 0)
    return;
}

Solution 12 - Java

    public boolean empty() {
    boolean isEmpty = true;
    int i = 0;
    for (int j = 0; j < array.length; j++) {
        if (array[j] != 0) {
            i++;
        }
    }
    if (i != 0) {
        isEmpty = false;
    }
    return isEmpty;
}

This is as close as I got to checking if an int array is empty. Although this will not work when the ints in the array are actually zero. It'll work for {1,2,3}, and it'll still return false if {2,0} but {0} will return true

Solution 13 - Java

I believe that what you want is

int[] k = new int[3];

if (k != null) {  // Note, != and not == as above
    System.out.println(k.length);
}

You newed it up so it was never going to be null.

Solution 14 - Java

You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.

int[] k = new int[3];
if(k.length == 0)
{
//do something
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkit SachanView Question on Stackoverflow
Solution 1 - JavacletusView Answer on Stackoverflow
Solution 2 - JavaShravan RamamurthyView Answer on Stackoverflow
Solution 3 - JavaMikeView Answer on Stackoverflow
Solution 4 - JavaJackkobecView Answer on Stackoverflow
Solution 5 - JavashahkalpeshView Answer on Stackoverflow
Solution 6 - JavaobjectsView Answer on Stackoverflow
Solution 7 - JavaShivang AgarwalView Answer on Stackoverflow
Solution 8 - JavahubbabubbaView Answer on Stackoverflow
Solution 9 - JavaUddhav P. GautamView Answer on Stackoverflow
Solution 10 - Javasaravana kumar ramasamyView Answer on Stackoverflow
Solution 11 - JavaunwindView Answer on Stackoverflow
Solution 12 - JavananatashView Answer on Stackoverflow
Solution 13 - JavavickirkView Answer on Stackoverflow
Solution 14 - JavaJ_fruittyView Answer on Stackoverflow