How to Check If a Stack Is Empty in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a Stack in Java is empty. We will explore different methods to achieve this, including the standard isEmpty() method and the size() method. You will also learn how to handle the case of a null stack.

Through hands-on examples, you will gain practical experience in using these techniques to determine the emptiness of a Java Stack, which is a fundamental operation when working with this data structure.


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(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/DataStructuresGroup -.-> java/arrays_methods("Arrays Methods") java/DataStructuresGroup -.-> java/collections_methods("Collections Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/if_else -.-> lab-559976{{"How to Check If a Stack Is Empty in Java"}} java/arrays_methods -.-> lab-559976{{"How to Check If a Stack Is Empty in Java"}} java/collections_methods -.-> lab-559976{{"How to Check If a Stack Is Empty in Java"}} java/exceptions -.-> lab-559976{{"How to Check If a Stack Is Empty in Java"}} java/object_methods -.-> lab-559976{{"How to Check If a Stack Is Empty in Java"}} end

Use isEmpty() for Stack Check

In this step, we will learn how to check if a Stack in Java is empty using the isEmpty() method. The Stack class is part of the Java Collections Framework and represents a last-in, first-out (LIFO) stack of objects. Checking if a stack is empty is a common operation when working with stacks, for example, before trying to remove an element.

The isEmpty() method is a simple and efficient way to determine if a collection, including a Stack, contains any elements. It returns true if the collection is empty (contains no elements), and false otherwise.

Let's create a simple Java program to demonstrate the isEmpty() method.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    import java.util.Stack;
    
    public class HelloJava {
        public static void main(String[] args) {
            // Create a new Stack
            Stack<String> stack = new Stack<>();
    
            // Check if the stack is empty using isEmpty()
            boolean isEmptyBeforePush = stack.isEmpty();
            System.out.println("Is the stack empty before pushing elements? " + isEmptyBeforePush);
    
            // Push some elements onto the stack
            stack.push("Element 1");
            stack.push("Element 2");
    
            // Check if the stack is empty after pushing elements
            boolean isEmptyAfterPush = stack.isEmpty();
            System.out.println("Is the stack empty after pushing elements? " + isEmptyAfterPush);
        }
    }

    Let's look at the new parts of this code:

    • import java.util.Stack;: This line imports the Stack class, making it available for use in our program.
    • Stack<String> stack = new Stack<>();: This line creates a new empty Stack that can hold String objects.
    • stack.isEmpty();: This is the method we are focusing on. It checks if the stack object is empty.
    • stack.push("...");: This method adds an element to the top of the stack.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, let's compile our modified program. In the Terminal, make sure you are in the ~/project directory. Then run:

    javac HelloJava.java

    If the compilation is successful, you will not see any output.

  5. Finally, let's run our program:

    java HelloJava

    You should see output similar to this:

    Is the stack empty before pushing elements? true
    Is the stack empty after pushing elements? false

    This output confirms that the isEmpty() method correctly reported the state of the stack before and after adding elements.

Check with size() Method

In the previous step, we used the isEmpty() method to check if a stack is empty. Another useful method for collections, including Stack, is the size() method. The size() method returns the number of elements currently in the collection. We can use this method to check if a stack is empty by seeing if its size is 0.

While isEmpty() is generally preferred for simply checking if a collection is empty because it can sometimes be more efficient, checking if size() == 0 achieves the same result. It's good to be aware of both methods.

Let's modify our program to use the size() method to check for emptiness.

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

  2. Modify the code to use size() == 0 instead of isEmpty():

    import java.util.Stack;
    
    public class HelloJava {
        public static void main(String[] args) {
            // Create a new Stack
            Stack<String> stack = new Stack<>();
    
            // Check if the stack is empty using size()
            boolean isEmptyBeforePush = stack.size() == 0;
            System.out.println("Is the stack empty before pushing elements? " + isEmptyBeforePush);
    
            // Push some elements onto the stack
            stack.push("Element A");
            stack.push("Element B");
            stack.push("Element C");
    
            // Check the size of the stack after pushing elements
            int sizeAfterPush = stack.size();
            System.out.println("Size of the stack after pushing elements: " + sizeAfterPush);
    
            // Check if the stack is empty after pushing elements using size()
            boolean isEmptyAfterPush = stack.size() == 0;
            System.out.println("Is the stack empty after pushing elements? " + isEmptyAfterPush);
        }
    }

    Notice the changes:

    • We replaced stack.isEmpty() with stack.size() == 0 to check for emptiness.
    • We also added a line to print the actual size of the stack after pushing elements using stack.size().
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java

    Again, no output means successful compilation.

  5. Run the program:

    java HelloJava

    You should see output similar to this:

    Is the stack empty before pushing elements? true
    Size of the stack after pushing elements: 3
    Is the stack empty after pushing elements? false

    This output shows that checking stack.size() == 0 correctly identifies an empty stack, and stack.size() returns the number of elements.

Test with Null Stack

In the previous steps, we learned how to check if a Stack is empty using isEmpty() and size(). It's also important to understand what happens if the Stack object itself is null. In Java, null means that a variable does not refer to any object. Trying to call a method on a null object will result in a NullPointerException, which is a common runtime error.

Let's see this in action and learn how to handle it.

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

  2. Modify the code to set the stack to null and then try to check if it's empty:

    import java.util.Stack;
    
    public class HelloJava {
        public static void main(String[] args) {
            // Create a new Stack and then set it to null
            Stack<String> stack = new Stack<>();
            stack.push("Some Element"); // Add an element first
            stack = null; // Now set the stack variable to null
    
            // Try to check if the stack is empty using isEmpty()
            try {
                boolean isEmpty = stack.isEmpty(); // This line will cause an error
                System.out.println("Is the stack empty? " + isEmpty);
            } catch (NullPointerException e) {
                System.out.println("Caught a NullPointerException! The stack object is null.");
            }
    
            // Try to check the size using size()
            try {
                 int size = stack.size(); // This line will also cause an error
                 System.out.println("Size of the stack: " + size);
            } catch (NullPointerException e) {
                 System.out.println("Caught a NullPointerException! Cannot get size of a null stack.");
            }
        }
    }

    Here's what's new:

    • stack = null;: This line makes the stack variable point to null. The Stack object we created earlier is no longer accessible through this variable.
    • try { ... } catch (NullPointerException e) { ... }: This is a try-catch block. It's used to handle potential errors (exceptions) that might occur during the execution of the code inside the try block. If a NullPointerException occurs, the code inside the catch block will be executed.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program in the Terminal:

    javac HelloJava.java

    Compilation should be successful.

  5. Run the program:

    java HelloJava

    You should see output similar to this:

    Caught a NullPointerException! The stack object is null.
    Caught a NullPointerException! Cannot get size of a null stack.

    This output shows that attempting to call isEmpty() or size() on a null stack variable results in a NullPointerException, and our try-catch blocks successfully handled these exceptions.

This demonstrates why it's crucial to ensure that an object is not null before calling methods on it. You can check if an object is null using a simple condition: if (stack != null) { ... }.

Summary

In this lab, we learned how to check if a Stack in Java is empty. We explored the primary method for this purpose, isEmpty(), which is part of the Java Collections Framework. We saw how to use isEmpty() to determine if a stack contains any elements, returning true for an empty stack and false otherwise.

We demonstrated the use of isEmpty() by creating a new Stack, checking its empty status before and after pushing elements, and printing the results. This hands-on exercise solidified our understanding of how to effectively use the isEmpty() method for stack emptiness checks in Java programs.