How to Check If a Queue Is Empty in Java

JavaJavaBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/DataStructuresGroup -.-> java/collections_methods("Collections Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/linkedlist("LinkedList") subgraph Lab Skills java/if_else -.-> lab-559972{{"How to Check If a Queue Is Empty in Java"}} java/collections_methods -.-> lab-559972{{"How to Check If a Queue Is Empty in Java"}} java/exceptions -.-> lab-559972{{"How to Check If a Queue Is Empty in Java"}} java/linkedlist -.-> lab-559972{{"How to Check If a Queue Is Empty in Java"}} end

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().

  1. Open the WebIDE and navigate to the ~/project directory in the File Explorer on the left.

  2. Right-click in the empty space in the File Explorer, select "New File", and name it QueueCheck.java.

  3. Open the QueueCheck.java file in the editor.

  4. 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; and import java.util.Queue;: These lines import the necessary classes to work with Queues. We are using LinkedList as a concrete implementation of the Queue interface.
    • Queue<String> myQueue = new LinkedList<>();: This line creates a new Queue object named myQueue that can hold String elements.
    • myQueue.isEmpty(): This is the method we are focusing on. It returns true if the queue contains no elements, and false otherwise.
    • myQueue.add("Element 1");: This adds an element to the end of the queue.
  5. Save the QueueCheck.java file (Ctrl+S or Cmd+S).

  6. Open the Terminal at the bottom of the WebIDE. Ensure you are in the ~/project directory. If not, type cd ~/project and press Enter.

  7. Compile the Java program by typing the following command and pressing Enter:

    javac QueueCheck.java

    If the compilation is successful, you will not see any output. A QueueCheck.class file will be created in the ~/project directory.

  8. Run the compiled Java program by typing the following command and pressing Enter:

    java QueueCheck

    You 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.

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

  2. Modify the main method to include checks using the size() method. Replace the existing main method 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.

  3. Save the modified QueueCheck.java file.

  4. Open the Terminal and ensure you are in the ~/project directory.

  5. Compile the updated Java program:

    javac QueueCheck.java
  6. Run the compiled program:

    java QueueCheck

    You 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.

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

  2. Modify the main method to include a check for a null queue. Replace the existing main method 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 myQueue within an if (myQueue != null) block. This ensures that we only call methods on myQueue if it is not null. We also added a section to demonstrate checking a variable explicitly set to null.

  3. Save the modified QueueCheck.java file.

  4. Open the Terminal and ensure you are in the ~/project directory.

  5. Compile the updated Java program:

    javac QueueCheck.java
  6. Run the compiled program:

    java QueueCheck

    You 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.