- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check whether a Stack is empty or not in Java
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
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("
The 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("
The 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("
The 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("
The stack elements are: " + stack); System.out.println("The stack is empty? " + stack.empty());