Check if Array Is Empty in Java

Check if array is empty in Java

In this post, we will see how to check if array is empty in Java.

The arrays are a data structure that facilitates storing multiple instances of data together in contiguous memory locations.

This article discusses different cases when an array is considered to be empty in Java. It also discusses methods to check, for different cases, if array is empty in Java.

Check if the Array Is Empty in Java

There are three different cases when Java considers an array to be empty. These are given as follows.

    • The array variable has the null reference.
    • The array does not contain any element.
    • The array has only null elements.

Let us understand each of these cases one by one.

The Array Variable Has the Null Reference

In this case, an array variable actually stores a null reference, therefore, storing virtually nothing. This case can arise from two different possibilities as given below.

  1. When the array is not instantiated, the array variable has a null reference making it an empty array. For example,
    > You should note that Java doesn’t allow you to use an uninitialized local variable. So this case does not apply to local variables. However, it is applicable if your array is globally declared.
  2. When you explicitly assign null to the array variable. For example,
    For this case when the array variable has a null reference, you can directly use the equality operator (==) to check if the array has the null reference.

Let us see the code to check this condition for Java arrays.

Output:

arr is empty (null).
arr2 is empty (null).

The Array Does Not Contain Any Element

When you declare an array as well as instantiate it, the memory is assigned to it. The array variable stores reference to the assigned memory.

However, if you instantiate the array with the size of the array as zero, it will not store any elements, therefore, making it an empty array.

To check if the array is empty in this case,

  • Check the length of the array using the ‘length’ variable.
  • The Java array object has a variable named ‘length’ that stores the number of elements in the array.
  • If the length is zero, the array is empty.

Let us see an example that implements the steps given above.

Output:

The array is empty

The Array Has Only Null Elements

Java initializes all the arrays of non-primitive types with null values at the time of instantiating the array. Therefore, if you do not assign non-null elements to the array, it will continue to contain the null values for all elements.

Alternatively, you can manually assign the null values to all of the array elements. In both cases, Java considers the array to be empty.

To check if the array is empty in this case,

  • Initialize a boolean flag variable to true.
  • Loop through all elements of the array.
  • Check each element for a null value.
    • If the current element is not null, change the value of the flag variable to false and break from the loop.
    • Otherwise, move to the next element.
  • After the loop terminates, check the flag variable.
    • If the flag is true, the array is empty.
    • Otherwise, the array is not empty.

Let us see the implementation of these steps in code.

Output:

The array is empty!

Note that the code declares a String array rather than an integer array as in previous cases. This is because the arrays with primitive data types are not initialized with null values by Java. For example, the integer array is initialized with zeros.

On the other hand, String is a class in Java, therefore, the String array is initialized with null values.

Using the Java Library to Check if the Array Is Empty in Java

Starting with the Java 8 version, Java provides library methods to perform a check on all array elements. Therefore, we can use these methods to check the condition of all null values in the array.

The java.util.Arrays class defines the stream() method that can be used to call the allMatch() method.

The stream() method returns a stream created using the array passed to it as a parameter. Let us see the definition of the stream() method.

The allMatch() method accepts a predicate (a condition to be checked) and returns a boolean value. The allMatch() method returns a boolean true if the condition is met on all the array values. Otherwise, it returns a boolean false. Let us see the definition of the allMatch() method.

Note that using this method you can only check the condition of the empty array where all elements of the array are null. Let us see the example in code.

The code passes the isNull predicate condition of the Objects class to the allMatch() method. It means that the allMatch() method returns true if all the elements of the array have null values.

Output:

The array is empty

Using Apache Commons Library to Check if the Array Is Empty in Java

The Apache commons library provides the isEmpty() method in the ArrayUtils class. This method can be used to check if the array is empty in Java.
You need to add below dependency to get Apache commons jar.

Let us see the definition of the isEmpty() method.

This method checks if the array passed to it as a parameter is empty or null. It returns a boolean true if an array is empty or null. Otherwise, it returns false.

Let us see the example demonstrating its use in the code.

Output:

The array 1 is empty
The array 2 is Null
The array 3 is not empty

You should note that this method only checks the following conditions.

  • The array variable has a null reference.
  • The array is of zero length.

It can not check if the array has all null values.

Conclusion

While working with arrays, especially in the cases where arrays are passed as parameters to methods, you should perform the checks for an empty array. This helps in preventing the unexpected failures of the program.

Apart from the direct methods, you can use the libraries to check the cases of the empty array in Java. However, you should be careful while using library methods. This is because, as we have discussed, both of the library methods work only for a subset of cases of an empty array.

Hope you have enjoyed reading the article. Stay tuned for more such articles.

Happy Learning!

Related Posts

  • 17 May

    How to Initialize an Array with 0 in Java

    Table of ContentsArraysInitializing Newly Created ArrayUsing Default Initialization of Arrays in JavaUsing Initialization After DeclarationUsing Simultaneous Initializing and Declaration of ArrayUsing Reflection in JavaInitializing Existing ArrayUsing the Arrays.fill() Function of JavaUsing the for LoopUsing Reassignment From Another ArrayUsing Collections.nCopies() Function of JavaInitializing User-Defined Object ArrayConclusion This article discusses the arrays and different ways to initialize […]

  • Set an array to another array in java
    23 April

    Set an Array Equal to Another Array in Java

    Table of ContentsSetting an Array Variable Equal to Another Array VariableSet an Array Equal to Another Array in Java Using the clone() MethodSet an Array Equal to Another Array in Java Using the arraycopy() MethodSet an Array Equal to Another Array in Java Using the copyOf() MethodSet an Array Equal to Another Array in Java […]

  • Initialize empty array in java
    01 January

    Initialize empty array in java

    Table of ContentsIntroductionHow do you initialize an empty array in java?Using new Keyword with predefined Values and SizeUsing Anonymous Array Objects to initialize empty arrayUsing java.util.Scanner Class for user input with predefined size. Using java.io.BufferedReader to initialize array for user input with unknown sizeUsing fill() method of java.util.Arrays Class to initialize empty array 💡 Outline You […]

  • Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers
    07 April

    Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers

    In this article, we look at a problem : Given an Array of Positive Integers, Find the [Maximum Difference](https://java2blog.com/maximum-difference-between-two-elements-in-array/ "Maximum Difference") between Two Adjacent Numbers. For each pair of elements we need to compute their difference and find the Maximum value of all the differences in array. Let us look at an example, Consider this […]

  • 11 November

    How to print array in java

    Learn about how to print array in java in multiple ways.

  • 09 October

    Initialize 2D array in Java

    Table of ContentsInitialize 2D array Using for loopInitialize 2D array using an initializerInitialize 2D array of variable columns lengthInitialize 2D array with heterogeneous dataInitialize 2D array using initialilzer with columnsInitialize 2D array using Reflection APIInitialize 2D array using the toCharArray() In this article, we will learn to initialize 2D array in Java. The array is […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.