How to Check If an Array Is Empty in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if an array in Java is empty. We will cover the fundamental technique of checking the array's length and also address how to handle cases where the array itself might be null. You will practice these concepts with different array types to solidify your understanding.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/DataStructuresGroup -.-> java/arrays("Arrays") java/DataStructuresGroup -.-> java/arrays_methods("Arrays Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") subgraph Lab Skills java/operators -.-> lab-560002{{"How to Check If an Array Is Empty in Java"}} java/if_else -.-> lab-560002{{"How to Check If an Array Is Empty in Java"}} java/arrays -.-> lab-560002{{"How to Check If an Array Is Empty in Java"}} java/arrays_methods -.-> lab-560002{{"How to Check If an Array Is Empty in Java"}} java/exceptions -.-> lab-560002{{"How to Check If an Array Is Empty in Java"}} end

Check Array Length for Zero

In this step, we will learn how to check if an array in Java is empty by checking its length. This is a fundamental operation when working with arrays to avoid errors.

First, let's create a new Java file named ArrayLengthCheck.java in your ~/project directory. You can do this using the WebIDE File Explorer on the left. Right-click in the ~/project area, select "New File", and type ArrayLengthCheck.java.

Now, open the ArrayLengthCheck.java file in the editor and add the following code:

public class ArrayLengthCheck {

    public static void main(String[] args) {
        // Declare and initialize an empty integer array
        int[] emptyArray = {};

        // Declare and initialize an integer array with elements
        int[] populatedArray = {1, 2, 3, 4, 5};

        // Check the length of the empty array
        if (emptyArray.length == 0) {
            System.out.println("emptyArray is empty.");
        } else {
            System.out.println("emptyArray is not empty. Length: " + emptyArray.length);
        }

        // Check the length of the populated array
        if (populatedArray.length == 0) {
            System.out.println("populatedArray is empty.");
        } else {
            System.out.println("populatedArray is not empty. Length: " + populatedArray.length);
        }
    }
}

Let's understand the new concepts here:

  • int[] emptyArray = {};: This declares an integer array named emptyArray and initializes it as an empty array.
  • int[] populatedArray = {1, 2, 3, 4, 5};: This declares an integer array named populatedArray and initializes it with five integer elements.
  • array.length: This is a property of an array in Java that gives you the number of elements in the array.
  • if (condition) { ... } else { ... }: This is an if-else statement, a fundamental control flow structure in programming. It allows your program to make decisions. If the condition inside the parentheses is true, the code inside the if block is executed. Otherwise, the code inside the else block is executed.

In this code, we are using the .length property to check if the length of each array is equal to 0. If it is, we print a message indicating that the array is empty. Otherwise, we print a message indicating that it's not empty and also print its length.

Save the file (Ctrl+S or Cmd+S).

Now, open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory. If not, use the command cd ~/project.

Compile the Java program using the javac command:

javac ArrayLengthCheck.java

If the compilation is successful, you will see no output. A ArrayLengthCheck.class file will be created in the ~/project directory.

Now, run the compiled program using the java command:

java ArrayLengthCheck

You should see the following output:

emptyArray is empty.
populatedArray is not empty. Length: 5

This output confirms that our program correctly identified the empty array and the populated array based on their lengths. Checking the length of an array before attempting to access its elements is a crucial step to prevent errors like ArrayIndexOutOfBoundsException, which occurs when you try to access an element at an index that doesn't exist in the array.

Handle Null Arrays

In the previous step, we learned how to check if an array is empty by checking its length. However, there's another important scenario to consider: what if the array itself is null?

In Java, a variable can hold a reference to an object, or it can hold the special value null, which means it doesn't refer to any object. If you try to access the .length property of an array variable that is null, your program will crash with a NullPointerException. This is a very common error in Java, so it's important to know how to handle it.

Let's modify our previous program to demonstrate and handle null arrays.

Open the ArrayLengthCheck.java file in the WebIDE editor.

Replace the existing code with the following:

public class ArrayLengthCheck {

    public static void main(String[] args) {
        // Declare an integer array but do not initialize it (it will be null)
        int[] nullArray = null;

        // Declare and initialize an empty integer array
        int[] emptyArray = {};

        // Declare and initialize an integer array with elements
        int[] populatedArray = {1, 2, 3, 4, 5};

        // Function to check if an array is null or empty
        checkArrayStatus(nullArray, "nullArray");
        checkArrayStatus(emptyArray, "emptyArray");
        checkArrayStatus(populatedArray, "populatedArray");
    }

    // A helper method to check and print the status of an array
    public static void checkArrayStatus(int[] arr, String arrayName) {
        System.out.println("Checking " + arrayName + "...");
        if (arr == null) {
            System.out.println(arrayName + " is null.");
        } else if (arr.length == 0) {
            System.out.println(arrayName + " is empty.");
        } else {
            System.out.println(arrayName + " is not empty. Length: " + arr.length);
        }
        System.out.println(); // Print a blank line for better readability
    }
}

Let's look at the changes:

  • int[] nullArray = null;: We declare an integer array variable nullArray and explicitly set its value to null.
  • public static void checkArrayStatus(int[] arr, String arrayName): We've created a new method called checkArrayStatus. This method takes an integer array (arr) and a string (arrayName) as input. This helps us reuse the logic for checking the array status.
  • if (arr == null): This is the crucial part for handling null arrays. We first check if the array variable arr is null using the equality operator ==. If it is null, we print a message and stop checking further conditions for this array.
  • else if (arr.length == 0): This check is only performed if the array is not null. If the array is not null, we then check if its length is 0 to see if it's empty.
  • The main method now calls checkArrayStatus for each of our arrays (nullArray, emptyArray, and populatedArray).

Save the file (Ctrl+S or Cmd+S).

Open the Terminal in the ~/project directory.

Compile the modified Java program:

javac ArrayLengthCheck.java

If the compilation is successful, run the program:

java ArrayLengthCheck

You should see the following output:

Checking nullArray...
nullArray is null.

Checking emptyArray...
emptyArray is empty.

Checking populatedArray...
populatedArray is not empty. Length: 5

This output shows that our program correctly identified the null array, the empty array, and the populated array. By checking for null before checking the length, we prevent the NullPointerException that would occur if we tried to access .length on a null array. This is a fundamental best practice in Java programming.

Test with Different Array Types

In the previous steps, we worked with an array of integers (int[]). It's important to understand that the concepts of checking for null and checking the .length property apply to arrays of any data type in Java, whether it's primitive types like int, double, or boolean, or object types like String or custom classes.

Let's modify our program one more time to demonstrate checking the status of arrays of different types.

Open the ArrayLengthCheck.java file in the WebIDE editor.

Replace the existing code with the following:

public class ArrayLengthCheck {

    public static void main(String[] args) {
        // Declare a null String array
        String[] nullStringArray = null;

        // Declare an empty double array
        double[] emptyDoubleArray = {};

        // Declare a boolean array with elements
        boolean[] populatedBooleanArray = {true, false, true};

        // Declare a String array with elements
        String[] populatedStringArray = {"apple", "banana", "cherry"};

        // Use the helper method to check different array types
        checkArrayStatus(nullStringArray, "nullStringArray");
        checkArrayStatus(emptyDoubleArray, "emptyDoubleArray");
        checkArrayStatus(populatedBooleanArray, "populatedBooleanArray");
        checkArrayStatus(populatedStringArray, "populatedStringArray");
    }

    // A generic helper method to check and print the status of an array
    // We use Object[] because it can represent an array of any object type
    // For primitive types, the check still works on the array reference itself
    public static void checkArrayStatus(Object arr, String arrayName) {
        System.out.println("Checking " + arrayName + "...");
        if (arr == null) {
            System.out.println(arrayName + " is null.");
        } else if (arr instanceof Object[]) {
            // For object arrays, we can cast and check length
            Object[] objectArray = (Object[]) arr;
            if (objectArray.length == 0) {
                 System.out.println(arrayName + " is empty.");
            } else {
                 System.out.println(arrayName + " is not empty. Length: " + objectArray.length);
            }
        } else if (arr.getClass().isArray()) {
             // For primitive arrays, we can't cast to Object[], but can still check length
             // using reflection or simply rely on the null check and the fact that
             // primitive arrays also have a .length property accessible directly
             // (though accessing it here would require more complex reflection)
             // For simplicity in this example, we'll just indicate it's a non-null, non-empty primitive array
             // A more robust check would involve reflection or overloaded methods for each primitive type
             try {
                 int length = java.lang.reflect.Array.getLength(arr);
                 if (length == 0) {
                     System.out.println(arrayName + " is empty.");
                 } else {
                     System.out.println(arrayName + " is not empty. Length: " + length);
                 }
             } catch (IllegalArgumentException e) {
                  System.out.println("Could not determine length for " + arrayName);
             }

        } else {
             System.out.println(arrayName + " is not an array.");
        }
        System.out.println(); // Print a blank line for better readability
    }
}

Let's look at the changes:

  • We've created arrays of different types: String[], double[], and boolean[].
  • The checkArrayStatus method now takes Object arr as a parameter. This allows it to accept arrays of any type, as all arrays in Java are objects.
  • Inside checkArrayStatus, we first check if arr is null.
  • If it's not null, we use instanceof Object[] to check if it's an array of objects. If it is, we cast it to Object[] and check its .length.
  • We also add a check arr.getClass().isArray() to see if the object is an array (this is true for both object arrays and primitive arrays).
  • For primitive arrays, accessing .length directly within this generic method is tricky without reflection. The provided code uses java.lang.reflect.Array.getLength(arr) as a more general way to get the length of any array type.

Save the file (Ctrl+S or Cmd+S).

Open the Terminal in the ~/project directory.

Compile the modified Java program:

javac ArrayLengthCheck.java

If the compilation is successful, run the program:

java ArrayLengthCheck

You should see output similar to this:

Checking nullStringArray...
nullStringArray is null.

Checking emptyDoubleArray...
emptyDoubleArray is empty.

Checking populatedBooleanArray...
populatedBooleanArray is not empty. Length: 3

Checking populatedStringArray...
populatedStringArray is not empty. Length: 4

This demonstrates that the principles of checking for null and checking the length apply consistently across different array types in Java. While the generic checkArrayStatus method using Object and reflection is more complex, the core idea of checking null first and then .length remains the same for specific array types (like int[], String[], etc.).

Summary

In this lab, we learned how to check if an array in Java is empty by examining its length property. We created a Java file ArrayLengthCheck.java and wrote code to declare both empty and populated integer arrays. By using an if-else statement and comparing the array's length to zero, we successfully determined whether each array was empty or not, printing the results to the console. This fundamental technique is crucial for preventing errors when working with arrays.