Introduction
In this lab, you will learn how to check if a Java List contains null elements. We will explore different methods to achieve this, starting with the straightforward contains() method. You will learn how to use contains(null) to quickly determine the presence of a null value in a list.
Following the initial check, the lab will guide you through iterating over a list to manually check each element for null. This approach provides more control and allows for handling scenarios with multiple null elements, which will also be covered. By the end of this lab, you will have a solid understanding of various techniques for identifying nulls within Java lists.
Use contains() for Null Check
In this step, we will explore how to check for the presence of null elements within a Java List using the contains() method. While contains() is generally used to check for specific elements, it can also be used to see if a List contains null.
First, let's create a new Java file. In the File Explorer on the left, right-click in the ~/project directory, select "New File", and name it NullCheckList.java.
Now, open NullCheckList.java in the editor and add the following code:
import java.util.List;
import java.util.ArrayList;
public class NullCheckList {
public static void main(String[] args) {
// Create a List and add some elements, including null
List<String> names = new ArrayList<>();
names.add("Alice");
names.add(null); // Adding a null element
names.add("Bob");
// Check if the list contains null using contains()
boolean containsNull = names.contains(null);
// Print the result
System.out.println("Does the list contain null? " + containsNull);
}
}
Let's break down the new parts of this code:
import java.util.List;andimport java.util.ArrayList;: These lines import the necessary classes to work withListandArrayList.List<String> names = new ArrayList<>();: This creates a newArrayListthat can holdStringobjects. We declare it as aListbecauseListis an interface thatArrayListimplements.names.add(null);: This line explicitly adds anullvalue to our list.boolean containsNull = names.contains(null);: This is the core of this step. We call thecontains()method on thenameslist, passingnullas the argument. The method returnstrueif the list containsnull, andfalseotherwise. The result is stored in a boolean variablecontainsNull.System.out.println("Does the list contain null? " + containsNull);: This line prints the result of our check to the console.
Save the file (Ctrl+S or Cmd+S).
Now, let's compile and run the program. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.
Compile the code using javac:
javac NullCheckList.java
If the compilation is successful (no output means success), run the compiled code using java:
java NullCheckList
You should see the output indicating whether the list contains null.
Loop Through List for Nulls
In the previous step, we used the contains() method to check if a list contains null. While simple, this method only tells us if null is present, not where it is or how many times it appears. A more common and flexible way to handle null elements in a list is to iterate through the list using a loop and check each element individually.
In this step, we will modify our NullCheckList.java program to loop through the list and identify the position (index) of any null elements.
Open the NullCheckList.java file in the WebIDE editor. Replace the existing main method with the following code:
import java.util.List;
import java.util.ArrayList;
public class NullCheckList {
public static void main(String[] args) {
// Create a List and add some elements, including null
List<String> names = new ArrayList<>();
names.add("Alice");
names.add(null); // Adding a null element
names.add("Bob");
names.add("Charlie");
names.add(null); // Adding another null element
System.out.println("Checking list for null elements:");
// Loop through the list using a for loop
for (int i = 0; i < names.size(); i++) {
// Get the element at the current index
String name = names.get(i);
// Check if the element is null
if (name == null) {
System.out.println("Null found at index: " + i);
}
}
}
}
Let's look at the changes:
- We added another
nullelement to the list to demonstrate finding multiplenulls. for (int i = 0; i < names.size(); i++): This is a standardforloop that iterates from index0up to (but not including) the size of thenameslist. The variableirepresents the current index.String name = names.get(i);: Inside the loop,names.get(i)retrieves the element at the current indexiand stores it in thenamevariable.if (name == null): This is the crucial check. We use the equality operator==to compare thenamevariable withnull. If they are equal, it means the element at the current index isnull.System.out.println("Null found at index: " + i);: If anullis found, this line prints a message indicating the index where it was found.
Save the file (Ctrl+S or Cmd+S).
Now, compile and run the modified program from the Terminal in the ~/project directory:
javac NullCheckList.java
java NullCheckList
You should see output indicating the indices where null elements were found in the list.
Checking list for null elements:
Null found at index: 1
Null found at index: 4
This approach gives us more detailed information about the null elements in the list, which is often necessary for handling them appropriately in your program.
Handle Multiple Null Elements
In the previous step, we successfully looped through a list and identified the indices of null elements. Now, let's expand on that and demonstrate how you might handle these null elements. "Handling" can mean different things depending on your program's logic, such as skipping the null element, replacing it with a default value, or performing a specific action.
In this step, we will modify our NullCheckList.java program again. This time, we will iterate through the list and print a different message for non-null elements compared to null elements.
Open the NullCheckList.java file in the WebIDE editor. Replace the existing main method with the following code:
import java.util.List;
import java.util.ArrayList;
public class NullCheckList {
public static void main(String[] args) {
// Create a List and add some elements, including null
List<String> names = new ArrayList<>();
names.add("Alice");
names.add(null); // Adding a null element
names.add("Bob");
names.add("Charlie");
names.add(null); // Adding another null element
names.add("David");
System.out.println("Processing list elements:");
// Loop through the list using a for-each loop
for (String name : names) {
// Check if the element is null
if (name == null) {
System.out.println("Found a null element, skipping.");
} else {
// If the element is not null, process it
System.out.println("Processing name: " + name);
}
}
}
}
Let's look at the changes in this version:
- We added one more non-null element (
"David") to the list. for (String name : names): This is an enhancedforloop (also known as a for-each loop). It's a convenient way to iterate over elements in a collection without using an index. In each iteration, the variablenamewill hold the current element from thenameslist.if (name == null): We still use the==operator to check if the current element (name) isnull.System.out.println("Found a null element, skipping.");: If the element isnull, we print a message indicating that we are skipping it. In a real application, you might perform a different action here, like logging the null or assigning a default value.else { System.out.println("Processing name: " + name); }: If the element is notnull, we enter theelseblock and print a message indicating that we are processing the non-null name.
Save the file (Ctrl+S or Cmd+S).
Now, compile and run the modified program from the Terminal in the ~/project directory:
javac NullCheckList.java
java NullCheckList
You should see output that processes the non-null names and indicates when a null element is encountered.
Processing list elements:
Processing name: Alice
Found a null element, skipping.
Processing name: Bob
Processing name: Charlie
Found a null element, skipping.
Processing name: David
This example demonstrates a basic way to handle null elements during iteration. Depending on your specific needs, you might replace null with a default string, remove the null elements from the list, or perform other operations. The key is to check for null before attempting to use the element, as trying to call methods on a null object will result in a NullPointerException.
Summary
In this lab, we learned how to check if a Java List contains null elements. We explored using the contains() method with null as the argument, which provides a straightforward way to determine the presence of a single null element.
We created a sample ArrayList, added both valid elements and a null value, and then used names.contains(null) to perform the check. The result was printed to the console, demonstrating the effectiveness of this method for a basic null check within a list.



