Saturday, September 6, 2025
HomeLanguagesJavaStack isEmpty() method in Java with Example

Stack isEmpty() method in Java with Example

The Java.util.Stack.isEmpty() method in Java is used to check and verify if a Stack is empty or not. It returns True if the Stack is empty else it returns False.

Syntax:

Stack.isEmpty()

Parameters: This method does not take any parameter.

Return Value: This function returns True if the Stackis empty else it returns False.

Below programs illustrate the Java.util.Stack.isEmpty() method:

Program 1:




// Java code to illustrate isEmpty()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<String> stack = new Stack<String>();
  
        // Use add() method to add elements into the Stack
        stack.add("Welcome");
        stack.add("To");
        stack.add("Geeks");
        stack.add("4");
        stack.add("Geeks");
  
        // Displaying the Stack
        System.out.println("Stack:  " + stack);
  
        // Verifying if the Stack is empty or not
        System.out.println("Is the Stack empty? "
                           + stack.isEmpty());
  
        // Clearing the Stack
        stack.clear();
  
        // Displaying the Stack
        System.out.println("Stack after clear(): "
                           + stack);
  
        // Verifying if the Stack is empty or not
        System.out.println("Is the Stack empty? "
                           + stack.isEmpty());
    }
}


Output:

Stack:  [Welcome, To, Geeks, 4, Geeks]
Is the Stack empty? false
Stack after clear(): []
Is the Stack empty? true

Program 2:




// Java code to illustrate isEmpty()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<Integer> stack = new Stack<Integer>();
  
        // Displaying the Stack
        System.out.println("Stack:  " + stack);
  
        // Verifying if the Stack is empty or not
        System.out.println("Is the Stack empty? "
                           + stack.isEmpty());
    }
}


Output:

Stack:  []
Is the Stack empty? true
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS