Check whether a Stack is empty or not in Java

Java 8Object Oriented ProgrammingProgramming

The method java.util.Stack.empty() is used to check if a stack is empty or not. This method requires no parameters. It returns true if the stack is empty and false if the stack is not empty.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Stack;
public class Demo {
   public static void main (String args[]) {
      Stack stack = new Stack();
      stack.push("Amy");
      stack.push("John");
      stack.push("Mary");
      System.out.println("The stack elements are: " + stack);
      System.out.println("The stack is empty? " + stack.empty());
      System.out.println("\nThe element that was popped is: " + stack.pop());
      System.out.println("The element that was popped is: " + stack.pop());
      System.out.println("The element that was popped is: " + stack.pop());
      System.out.println("\nThe stack elements are: " + stack);
      System.out.println("The stack is empty? " + stack.empty());
   }
}

Output

The stack elements are: [Amy, John, Mary]
The stack is empty? false
The element that was popped is: Mary
The element that was popped is: John
The element that was popped is: Amy
The stack elements are: []
The stack is empty? true

Now let us understand the above program.

The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed and then the Stack.empty() method is used to check if a stack is empty or not. A code snippet which demonstrates this is as follows −

Stack stack = new Stack();
stack.push("Amy");
stack.push("John");
stack.push("Mary");
System.out.println("The stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());

The Stack.pop() method is used to pop the three stack elements. The stack is displayed and then the Stack.empty() method is used to check if a stack is empty or not. A code snippet which demonstrates this is as follows −

System.out.println("\nThe element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("\nThe stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
raja
Published on 10-Jan-2019 08:29:46
Advertisements