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.
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.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.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 theStackclass, making it available for use in our program.Stack<String> stack = new Stack<>();: This line creates a new emptyStackthat can holdStringobjects.stack.isEmpty();: This is the method we are focusing on. It checks if thestackobject is empty.stack.push("...");: This method adds an element to the top of the stack.
Save the file (Ctrl+S or Cmd+S).
Now, let's compile our modified program. In the Terminal, make sure you are in the
~/projectdirectory. Then run:javac HelloJava.javaIf the compilation is successful, you will not see any output.
Finally, let's run our program:
java HelloJavaYou should see output similar to this:
Is the stack empty before pushing elements? true Is the stack empty after pushing elements? falseThis 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.
Open the
HelloJava.javafile in the WebIDE editor.Modify the code to use
size() == 0instead ofisEmpty():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()withstack.size() == 0to check for emptiness. - We also added a line to print the actual size of the stack after pushing elements using
stack.size().
- We replaced
Save the file (Ctrl+S or Cmd+S).
Compile the modified program in the Terminal:
javac HelloJava.javaAgain, no output means successful compilation.
Run the program:
java HelloJavaYou 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? falseThis output shows that checking
stack.size() == 0correctly identifies an empty stack, andstack.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.
Open the
HelloJava.javafile in the WebIDE editor.Modify the code to set the stack to
nulland 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 thestackvariable point tonull. TheStackobject we created earlier is no longer accessible through this variable.try { ... } catch (NullPointerException e) { ... }: This is atry-catchblock. It's used to handle potential errors (exceptions) that might occur during the execution of the code inside thetryblock. If aNullPointerExceptionoccurs, the code inside thecatchblock will be executed.
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaCompilation should be successful.
Run the program:
java HelloJavaYou 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()orsize()on anullstack variable results in aNullPointerException, and ourtry-catchblocks 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.



