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.
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.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.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 namednamesthat can holdStringobjects. We then immediately assign the valuenullto it. This means the variablenamesdoesn't currently refer to any actual array object in memory.if (names == null): This is anifstatement, 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 thenamesvariable is equal tonull.System.out.println("The 'names' array is null.");: This line will be executed only if the conditionnames == nullis true.System.out.println("The 'names' array is not null.");: This line will be executed only if the conditionnames == nullis false (meaningnamesis notnull).
Save the file (Ctrl+S or Cmd+S).
Compile the modified program. In the Terminal, run:
javac HelloJava.javaIf the compilation is successful, you won't see any output.
Run the compiled program:
java HelloJavaYou should see the following output:
The 'names' array is null.This output confirms that our check correctly identified the
namesarray reference asnull.
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.
Open the
HelloJava.javafile in the WebIDE editor.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 anullarray. - 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 thenamesarray reference is notnull.&&: 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 thenamesarray 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 theNullPointerException.
- The
elseblock now prints a message indicating that the array is eithernullor empty.
- We kept
Save the file (Ctrl+S or Cmd+S).
Compile the modified program:
javac HelloJava.javaAgain, if successful, there will be no output.
Run the compiled program:
java HelloJavaYou 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
nullor empty. Since we initialized it tonull, the first part of theifcondition (names != null) was false, and theelseblock 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.
Open the
HelloJava.javafile in the WebIDE editor.Modify the line where we declare and initialize the
namesarray. ChangeString[] names = null;toString[] names = new String[0];. The rest of the code, including theifstatement 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 ofStringobjects with a size of 0. The variablenamesnow refers to an actual array object in memory, but that array contains no elements. It is notnull.
Save the file (Ctrl+S or Cmd+S).
Compile the modified program:
javac HelloJava.javaIf the compilation is successful, there will be no output.
Run the compiled program:
java HelloJavaYou 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. Ourifcondition isif (names != null && names.length > 0).names != null: This part is now true becausenamesrefers 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 theelseblock 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.



