How to Check If an Array Is Null in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if an array in Java is null. We will start by understanding how to check if an array reference itself is null to prevent NullPointerExceptions.

Following that, we will explore how to combine null checks with length checks for more robust array handling. Finally, you will test your understanding by working with an initialized empty array.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/DataStructuresGroup -.-> java/arrays("Arrays") subgraph Lab Skills java/if_else -.-> lab-560003{{"How to Check If an Array Is Null in Java"}} java/arrays -.-> lab-560003{{"How to Check If an Array Is Null in Java"}} end

Check Array Reference for Null

In this step, we will learn how to check if an array reference in Java is null. Checking for null is a fundamental practice in Java programming to prevent NullPointerExceptions, which are common runtime errors.

A NullPointerException occurs when you try to use a variable that refers to nothing (it's null) as if it were an object. Imagine trying to open a box that doesn't exist – that's similar to what happens when you get a NullPointerException.

Let's create a simple Java program to demonstrate how to check for a null array reference.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    public class HelloJava {
        public static void main(String[] args) {
            String[] names = null; // Declaring an array reference and setting it to null
    
            // Check if the array reference is null before trying to use it
            if (names == null) {
                System.out.println("The 'names' array is null.");
            } else {
                System.out.println("The 'names' array is not null.");
            }
        }
    }

    Let's look at the new parts of this code:

    • String[] names = null;: This line declares an array variable named names that can hold String objects. We then immediately assign the value null to it. This means the variable names doesn't currently refer to any actual array object in memory.
    • if (names == null): This is an if statement, which is used to make decisions in programming. It checks if the condition inside the parentheses (names == null) is true. The == operator is used to compare if the names variable is equal to null.
    • System.out.println("The 'names' array is null.");: This line will be executed only if the condition names == null is true.
    • System.out.println("The 'names' array is not null.");: This line will be executed only if the condition names == null is false (meaning names is not null).
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program. In the Terminal, run:

    javac HelloJava.java

    If the compilation is successful, you won't see any output.

  5. Run the compiled program:

    java HelloJava

    You should see the following output:

    The 'names' array is null.

    This output confirms that our check correctly identified the names array reference as null.

Understanding how to check for null is crucial for writing robust Java code. In the next step, we'll explore what happens when we try to access the length of an array that is null and how to combine checks.

Combine Null and Length Checks

In the previous step, we learned how to check if an array reference is null. Now, let's explore what happens when we try to access the length of a null array and how to combine the null check with a check for the array's length.

Attempting to access the .length property of a null array reference will result in a NullPointerException. This is because you are trying to access a property of something that doesn't exist.

Let's modify our program to demonstrate this and then add a combined check.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the entire contents of the file with the following code:

    public class HelloJava {
        public static void main(String[] args) {
            String[] names = null; // Declaring an array reference and setting it to null
    
            // Attempting to access the length of a null array (will cause an error)
            // int length = names.length; // Uncommenting this line would cause a NullPointerException
    
            // Combine null check and length check
            if (names != null && names.length > 0) {
                System.out.println("The 'names' array is not null and has elements.");
            } else {
                System.out.println("The 'names' array is null or empty.");
            }
        }
    }

    Here's what's new or changed:

    • We kept String[] names = null; to start with a null array.
    • The commented-out line // int length = names.length; shows what would happen if we tried to access the length directly. We've commented it out so the program doesn't crash immediately.
    • if (names != null && names.length > 0): This is the combined check.
      • names != null: This part checks if the names array reference is not null.
      • &&: This is the logical AND operator. Both conditions on either side of && must be true for the entire condition to be true.
      • names.length > 0: This part checks if the length of the names array is greater than 0. This check is only performed if the first part (names != null) is true, thanks to the short-circuiting nature of the && operator in Java. This prevents the NullPointerException.
    • The else block now prints a message indicating that the array is either null or empty.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program:

    javac HelloJava.java

    Again, if successful, there will be no output.

  5. Run the compiled program:

    java HelloJava

    You should see the following output:

    The 'names' array is null or empty.

    This output shows that our combined check correctly identified that the array was either null or empty. Since we initialized it to null, the first part of the if condition (names != null) was false, and the else block was executed.

Combining checks like this is a standard way to safely handle array references in Java, ensuring you don't encounter NullPointerExceptions when checking properties like length or accessing elements.

Test with Initialized Empty Array

In the previous steps, we learned about checking for null array references and combining that with a length check. We saw that our combined check correctly identified a null array.

Now, let's test our combined check with an array that is not null but is empty (has a length of 0). This is another common scenario you'll encounter.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Modify the line where we declare and initialize the names array. Change String[] names = null; to String[] names = new String[0];. The rest of the code, including the if statement with the combined check, should remain the same.

    The updated code should look like this:

    public class HelloJava {
        public static void main(String[] args) {
            String[] names = new String[0]; // Declaring and initializing an empty array
    
            // Combine null check and length check
            if (names != null && names.length > 0) {
                System.out.println("The 'names' array is not null and has elements.");
            } else {
                System.out.println("The 'names' array is null or empty.");
            }
        }
    }

    Here's the change:

    • String[] names = new String[0];: This line now creates a new array of String objects with a size of 0. The variable names now refers to an actual array object in memory, but that array contains no elements. It is not null.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program:

    javac HelloJava.java

    If the compilation is successful, there will be no output.

  5. Run the compiled program:

    java HelloJava

    You should see the following output:

    The 'names' array is null or empty.

    This output is the same as when the array was null. Let's understand why. Our if condition is if (names != null && names.length > 0).

    • names != null: This part is now true because names refers to an empty array object.
    • names.length > 0: This part checks if the length of the array is greater than 0. Since the array has a length of 0, this condition is false.
    • Because the second part of the && condition is false, the entire condition (names != null && names.length > 0) evaluates to false, and the else block is executed.

This demonstrates that our combined check correctly identifies both null arrays and empty arrays, which is often the desired behavior when you want to process an array only if it contains elements.

Summary

In this lab, we learned how to check if an array reference in Java is null to prevent NullPointerExceptions. We started by creating a simple program to demonstrate checking a null array reference using an if statement and the == operator.

We then explored combining the null check with a length check to handle cases where the array is not null but might be empty. Finally, we tested our combined check with an initialized empty array to understand the difference between a null array reference and an empty array.