Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

People also ask

Is an empty array null Javascript?

isArray() method. This method returns true if the Object passed as a parameter is an array. It also checks for the case if the array is undefined or null. The array can be checked if it is empty by using the array.

How check if array is empty C?

There's no such thing as an "empty array" or an "empty element" in C. The array always holds a fixed pre-determined number of elements and each element always holds some value. The only way to introduce the concept of an "empty" element is to implement it yourself.

How do you check if an array is empty or not in Javascript?

length > 0) returns true if array = null . !( typeof array != "undefined" || array. length > 0) returns false if array = [1,2] .


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;
  }
}

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


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) { }

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);