Introduction
In this lab, you will learn how to check if a Queue in Java is empty. This is a crucial skill for preventing errors when working with queues.
We will explore the primary method for this check, isEmpty(), and also see how to verify the queue's state using the size() method. Additionally, we will cover how to handle scenarios where the queue might be null. Through hands-on examples, you will gain practical experience in determining the emptiness of a Java queue.
Use isEmpty() for Queue Check
In this step, we will explore how to check if a Queue in Java is empty using the isEmpty() method. This is a fundamental operation when working with collections, as it allows us to avoid errors that might occur when trying to access elements from an empty queue.
First, let's create a simple Java program that demonstrates the use of isEmpty().
Open the WebIDE and navigate to the
~/projectdirectory in the File Explorer on the left.Right-click in the empty space in the File Explorer, select "New File", and name it
QueueCheck.java.Open the
QueueCheck.javafile in the editor.Copy and paste the following code into the editor:
import java.util.LinkedList; import java.util.Queue; public class QueueCheck { public static void main(String[] args) { // Create a Queue using LinkedList Queue<String> myQueue = new LinkedList<>(); // Check if the queue is empty boolean isEmptyBeforeAdd = myQueue.isEmpty(); System.out.println("Is the queue empty before adding elements? " + isEmptyBeforeAdd); // Add some elements to the queue myQueue.add("Element 1"); myQueue.add("Element 2"); // Check if the queue is empty again boolean isEmptyAfterAdd = myQueue.isEmpty(); System.out.println("Is the queue empty after adding elements? " + isEmptyAfterAdd); } }Let's quickly go over the new parts of this code:
import java.util.LinkedList;andimport java.util.Queue;: These lines import the necessary classes to work with Queues. We are usingLinkedListas a concrete implementation of theQueueinterface.Queue<String> myQueue = new LinkedList<>();: This line creates a newQueueobject namedmyQueuethat can holdStringelements.myQueue.isEmpty(): This is the method we are focusing on. It returnstrueif the queue contains no elements, andfalseotherwise.myQueue.add("Element 1");: This adds an element to the end of the queue.
Save the
QueueCheck.javafile (Ctrl+S or Cmd+S).Open the Terminal at the bottom of the WebIDE. Ensure you are in the
~/projectdirectory. If not, typecd ~/projectand press Enter.Compile the Java program by typing the following command and pressing Enter:
javac QueueCheck.javaIf the compilation is successful, you will not see any output. A
QueueCheck.classfile will be created in the~/projectdirectory.Run the compiled Java program by typing the following command and pressing Enter:
java QueueCheckYou should see output similar to this:
Is the queue empty before adding elements? true Is the queue empty after adding elements? false
This output confirms that the isEmpty() method correctly reported the state of the queue before and after adding elements. Using isEmpty() is the recommended way to check if a collection is empty, as it is generally more efficient than checking if the size is zero, especially for certain collection implementations.
Verify with size() Method
In the previous step, we learned how to use the isEmpty() method to check if a queue is empty. Another way to determine if a collection is empty is by checking its size. The size() method returns the number of elements in the collection. If the size is 0, the collection is empty.
While isEmpty() is generally preferred for checking emptiness due to potential performance benefits with certain collection types, understanding how to use size() is also important.
Let's modify our QueueCheck.java program to also use the size() method.
Open the
QueueCheck.javafile in the WebIDE editor.Modify the
mainmethod to include checks using thesize()method. Replace the existingmainmethod with the following code:import java.util.LinkedList; import java.util.Queue; public class QueueCheck { public static void main(String[] args) { // Create a Queue using LinkedList Queue<String> myQueue = new LinkedList<>(); // Check if the queue is empty using isEmpty() boolean isEmptyBeforeAdd = myQueue.isEmpty(); System.out.println("Is the queue empty before adding elements (isEmpty())? " + isEmptyBeforeAdd); // Check if the queue is empty using size() boolean isEmptyBySizeBeforeAdd = (myQueue.size() == 0); System.out.println("Is the queue empty before adding elements (size() == 0)? " + isEmptyBySizeBeforeAdd); // Add some elements to the queue myQueue.add("Element 1"); myQueue.add("Element 2"); // Check if the queue is empty again using isEmpty() boolean isEmptyAfterAdd = myQueue.isEmpty(); System.out.println("Is the queue empty after adding elements (isEmpty())? " + isEmptyAfterAdd); // Check if the queue is empty again using size() boolean isEmptyBySizeAfterAdd = (myQueue.size() == 0); System.out.println("Is the queue empty after adding elements (size() == 0)? " + isEmptyBySizeAfterAdd); // Print the size of the queue System.out.println("Current queue size: " + myQueue.size()); } }In this updated code, we've added lines to check if the queue's
size()is equal to 0 both before and after adding elements. We also print the final size of the queue.Save the modified
QueueCheck.javafile.Open the Terminal and ensure you are in the
~/projectdirectory.Compile the updated Java program:
javac QueueCheck.javaRun the compiled program:
java QueueCheckYou should now see output similar to this:
Is the queue empty before adding elements (isEmpty())? true Is the queue empty before adding elements (size() == 0)? true Is the queue empty after adding elements (isEmpty())? false Is the queue empty after adding elements (size() == 0)? false Current queue size: 2
As you can see, both isEmpty() and checking if size() == 0 give the same result for determining if the queue is empty. The size() method is also useful for knowing exactly how many elements are currently in the queue.
Handle Null Queues
In the previous steps, we worked with a Queue object that was properly initialized. However, in real-world programming, it's possible to encounter situations where a reference to a Queue (or any object) is null. Attempting to call a method on a null object will result in a NullPointerException, which is a common runtime error in Java.
It's crucial to handle potential null references to prevent these errors. Before calling methods like isEmpty() or size() on a Queue, you should always check if the queue reference itself is null.
Let's modify our QueueCheck.java program one more time to demonstrate how to handle a null queue.
Open the
QueueCheck.javafile in the WebIDE editor.Modify the
mainmethod to include a check for anullqueue. Replace the existingmainmethod with the following code:import java.util.LinkedList; import java.util.Queue; public class QueueCheck { public static void main(String[] args) { // Create a Queue using LinkedList Queue<String> myQueue = new LinkedList<>(); // Check if the queue is null before checking emptiness or size if (myQueue != null) { // Check if the queue is empty using isEmpty() boolean isEmptyBeforeAdd = myQueue.isEmpty(); System.out.println("Is the queue empty before adding elements (isEmpty())? " + isEmptyBeforeAdd); // Check if the queue is empty using size() boolean isEmptyBySizeBeforeAdd = (myQueue.size() == 0); System.out.println("Is the queue empty before adding elements (size() == 0)? " + isEmptyBySizeBeforeAdd); // Add some elements to the queue myQueue.add("Element 1"); myQueue.add("Element 2"); // Check if the queue is empty again using isEmpty() boolean isEmptyAfterAdd = myQueue.isEmpty(); System.out.println("Is the queue empty after adding elements (isEmpty())? " + isEmptyAfterAdd); // Check if the queue is empty again using size() boolean isEmptyBySizeAfterAdd = (myQueue.size() == 0); System.out.println("Is the queue empty after adding elements (size() == 0)? " + isEmptyBySizeAfterAdd); // Print the size of the queue System.out.println("Current queue size: " + myQueue.size()); } else { System.out.println("The queue is null. Cannot perform operations."); } // Example with a null queue reference Queue<String> nullQueue = null; // Attempting to check isEmpty() or size() on nullQueue without a null check would cause a NullPointerException System.out.println("\nChecking a potentially null queue:"); if (nullQueue != null) { boolean isNullQueueEmpty = nullQueue.isEmpty(); System.out.println("Is the null queue empty? " + isNullQueueEmpty); } else { System.out.println("The null queue is indeed null. Handled correctly."); } } }We've wrapped the original code that operates on
myQueuewithin anif (myQueue != null)block. This ensures that we only call methods onmyQueueif it is notnull. We also added a section to demonstrate checking a variable explicitly set tonull.Save the modified
QueueCheck.javafile.Open the Terminal and ensure you are in the
~/projectdirectory.Compile the updated Java program:
javac QueueCheck.javaRun the compiled program:
java QueueCheckYou should see output similar to this:
Is the queue empty before adding elements (isEmpty())? true Is the queue empty before adding elements (size() == 0)? true Is the queue empty after adding elements (isEmpty())? false Is the queue empty after adding elements (size() == 0)? false Current queue size: 2 Checking a potentially null queue: The null queue is indeed null. Handled correctly.
This output shows that our code correctly handles both the case where the queue is initialized and the case where the queue reference is null, preventing a NullPointerException. Always remember to check for null when dealing with object references in Java, especially when they might come from external sources or be the result of operations that could return null.
Summary
In this lab, we learned how to check if a Queue in Java is empty. We primarily focused on using the isEmpty() method, which is the standard and recommended way to perform this check. We created a simple Java program to demonstrate how isEmpty() returns true for an empty queue and false after elements are added.
Additionally, we explored the size() method as an alternative way to check for emptiness, noting that a size of 0 indicates an empty queue. Finally, we discussed the importance of handling potential NullPointerException by checking if a queue object is null before attempting to call methods on it.



