Introduction
In this lab, you will learn how to check if a Java array contains null elements. Handling null values is a fundamental skill in Java programming to prevent common errors like NullPointerException. We will explore three different methods to achieve this: iterating through the array using a loop, leveraging the power of the Stream API, and counting the number of null elements present in the array. By the end of this lab, you will be equipped with practical techniques to effectively identify and manage null values within your Java arrays.
Loop Through Array for Null Check
In this step, we will learn how to check for null values in a Java array by looping through its elements. Handling null values is crucial in Java to prevent NullPointerExceptions, which are common errors.
A null value in Java means that a variable does not refer to any object. When you try to access a method or a field of a variable that is null, a NullPointerException occurs, causing your program to crash.
Let's create a simple Java program to demonstrate how to loop through an array and check for null elements.
Open the
HelloJava.javafile in the WebIDE editor. If you don't have it open, you can find it in the File Explorer on the left, inside theprojectfolder.Replace the existing code in
HelloJava.javawith the following code:public class HelloJava { public static void main(String[] args) { String[] names = new String[5]; // Declare an array of Strings with size 5 names[0] = "Alice"; names[1] = "Bob"; names[2] = null; // Assign a null value names[3] = "Charlie"; names[4] = null; // Assign another null value System.out.println("Checking array for null values:"); // Loop through the array for (int i = 0; i < names.length; i++) { // Check if the current element is null if (names[i] == null) { System.out.println("Element at index " + i + " is null."); } else { System.out.println("Element at index " + i + " is: " + names[i]); } } } }Let's look at the new parts of this code:
String[] names = new String[5];: This line declares an array namednamesthat can hold 5Stringobjects. When you create an array of objects like this, the elements are automatically initialized tonull.names[2] = null;andnames[4] = null;: We are explicitly assigningnullto the elements at index 2 and 4.for (int i = 0; i < names.length; i++): This is a standardforloop that iterates through the array from the first element (index 0) to the last element (names.length - 1).if (names[i] == null): Inside the loop, thisifstatement checks if the element at the current indexiis equal tonull.System.out.println("Element at index " + i + " is null.");: If the element isnull, this line is executed.System.out.println("Element at index " + i + " is: " + names[i]);: If the element is notnull, this line is executed, printing the value of the element.
Save the
HelloJava.javafile (Ctrl+S or Cmd+S).Now, compile the modified program. Open the Terminal at the bottom of the WebIDE and run the following command:
javac HelloJava.javaIf there are no errors, the compilation is successful.
Finally, run the compiled program:
java HelloJavaYou should see output similar to this:
Checking array for null values: Element at index 0 is: Alice Element at index 1 is: Bob Element at index 2 is null. Element at index 3 is: Charlie Element at index 4 is null.This output shows that our program successfully identified and reported the
nullelements in the array.
In this step, you've learned how to manually loop through a Java array and check each element for a null value using a simple if condition. This is a fundamental technique for handling potential NullPointerExceptions.
Use Stream API to Detect Nulls
In the previous step, we used a traditional for loop to check for null values in an array. Java 8 introduced the Stream API, which provides a more functional and often more concise way to process collections of data, including arrays. In this step, we will learn how to use the Stream API to detect null elements.
The Stream API allows you to perform operations on a sequence of elements in a declarative way. This means you describe what you want to do, rather than how to do it (like with a for loop).
Let's modify our HelloJava.java program to use the Stream API to find and print the null elements.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
import java.util.Arrays; // Import the Arrays class import java.util.Objects; // Import the Objects class public class HelloJava { public static void main(String[] args) { String[] names = new String[5]; names[0] = "Alice"; names[1] = "Bob"; names[2] = null; names[3] = "Charlie"; names[4] = null; System.out.println("Checking array for null values using Stream API:"); // Convert the array to a Stream Arrays.stream(names) // Filter for null elements .filter(Objects::isNull) // Print each null element (or a message indicating null) .forEach(name -> System.out.println("Found a null element.")); } }Let's break down the new parts:
import java.util.Arrays;: We need to import theArraysclass to use itsstream()method.import java.util.Objects;: We import theObjectsclass to use theisNull()method, which is a convenient way to check if an object isnull.Arrays.stream(names): This line converts ournamesarray into aStreamofStringobjects..filter(Objects::isNull): This is an intermediate operation. It filters the stream, keeping only the elements for which the conditionObjects.isNull(element)is true (i.e., the elements that arenull).Objects::isNullis a method reference, a shorthand for a lambda expressionname -> Objects.isNull(name)..forEach(name -> System.out.println("Found a null element."));: This is a terminal operation. It performs an action for each element remaining in the stream (which are thenullelements after filtering). In this case, it prints "Found a null element." for eachnullfound.
Save the
HelloJava.javafile.Compile the program in the Terminal:
javac HelloJava.javaRun the program:
java HelloJavaYou should see output similar to this:
Checking array for null values using Stream API: Found a null element. Found a null element.This output confirms that the Stream API successfully identified the two
nullelements in the array. Using streams can make your code more readable and expressive for certain operations like filtering and processing collections.
Count Null Elements
In the previous steps, we learned how to identify null elements in an array using both a for loop and the Stream API. Sometimes, instead of just identifying the null elements, you might need to know exactly how many null elements are present in an array. In this step, we will learn how to count the number of null elements using the Stream API.
The Stream API provides a convenient method called count() which, when applied to a stream, returns the number of elements in that stream. We can combine this with the filter() operation we used before to count only the null elements.
Let's modify our HelloJava.java program one more time to count the null elements and print the total count.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
import java.util.Arrays; import java.util.Objects; public class HelloJava { public static void main(String[] args) { String[] names = new String[5]; names[0] = "Alice"; names[1] = "Bob"; names[2] = null; names[3] = "Charlie"; names[4] = null; System.out.println("Counting null values using Stream API:"); // Convert the array to a Stream long nullCount = Arrays.stream(names) // Filter for null elements .filter(Objects::isNull) // Count the remaining elements (which are null) .count(); System.out.println("Total number of null elements: " + nullCount); } }Here's what's new:
long nullCount = ... .count();: After filtering the stream to include onlynullelements, we call thecount()terminal operation. This operation returns the number of elements in the filtered stream as alongvalue, which we store in thenullCountvariable.System.out.println("Total number of null elements: " + nullCount);: This line prints the final count ofnullelements.
Save the
HelloJava.javafile.Compile the program in the Terminal:
javac HelloJava.javaRun the program:
java HelloJavaYou should see the following output:
Counting null values using Stream API: Total number of null elements: 2This output shows that our program correctly counted the two
nullelements in the array. Using the Stream API'sfilter()andcount()methods together is an efficient and readable way to count specific types of elements in a collection, includingnullvalues.
You have now learned three different ways to handle null values in a Java array: using a traditional for loop to check each element, using the Stream API to filter and identify null elements, and using the Stream API to filter and count null elements. These techniques are fundamental for writing robust Java code that avoids NullPointerExceptions.
Summary
In this lab, we learned how to check for null elements in a Java array using different approaches. We started by implementing a traditional loop to iterate through the array and explicitly check each element for a null value using an if condition. This method provides a clear and fundamental way to identify nulls and is useful for understanding the basic concept of null handling in arrays.
We then explored more modern and concise techniques for null detection. The lab demonstrated how to leverage the Java Stream API to efficiently check for nulls. This approach utilizes stream operations to process the array elements and determine the presence of nulls in a more functional style. Finally, we learned how to count the number of null elements within an array, providing a way to quantify the extent of null values present. These methods offer different levels of expressiveness and efficiency for handling nulls in Java arrays.



