Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Stack search() Method in Java
Next article icon

Stack empty() Method in Java

Last Updated : 24 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The java.util.Stack.empty() method in Java is used to check whether a stack is empty or not. The method is of boolean type and returns true if the stack is empty else false. 

Syntax:

STACK.empty()

Parameters: The method does not take any parameters. 

Return Value: The method returns boolean true if the stack is empty else it returns false. 

Below programs illustrate the working of java.util.Stack.empty() method:

Program 1: 

Java
// Java code to demonstrate empty() method import java.util.*;  public class Stack_Demo {     public static void main(String[] args)     {          // Creating an empty Stack         Stack<String> STACK = new Stack<String>();          // Stacking strings         STACK.push("Geeks");         STACK.push("4");         STACK.push("Geeks");         STACK.push("Welcomes");         STACK.push("You");          // Displaying the Stack         System.out.println("The stack is: " + STACK);          // Checking for the emptiness of stack         System.out.println("Is the stack empty? " +                                     STACK.empty());          // Popping out all the elements         STACK.pop();         STACK.pop();         STACK.pop();         STACK.pop();         STACK.pop();          // Checking for the emptiness of stack         System.out.println("Is the stack empty? " +                                     STACK.empty());     } } 

Output
The stack is: [Geeks, 4, Geeks, Welcomes, You] Is the stack empty? false Is the stack empty? true

Program 2: 

Java
// Java code to demonstrate empty() method import java.util.*;  public class Stack_Demo {     public static void main(String[] args)     {          // Creating an empty Stack         Stack<Integer> STACK = new Stack<Integer>();          // Stacking int values         STACK.push(8);         STACK.push(5);         STACK.push(9);         STACK.push(2);         STACK.push(4);          // Displaying the Stack         System.out.println("The stack is: " + STACK);          // Checking for the emptiness of stack         System.out.println("Is the stack empty? " +                                     STACK.empty());     } } 

Output
The stack is: [8, 5, 9, 2, 4] Is the stack empty? false

Program 3:  How to travel through Stack using java.util.Stack.empty() method to get sum of all elements

Java
// Java code to demonstrate Traversal in Stack using empty() method import java.util.*;  public class Stack_Demo {     public static void main(String[] args)     {          // Creating an empty Stack         Stack<Integer> STACK = new Stack<>();         // You can also Initialize Stack as below         // both are same way         // Stack<Integer> STACK = new Stack<Integer>();          // Stack Pushing Elements         STACK.push(23);         STACK.push(3);         STACK.push(-30);         STACK.push(13);         STACK.push(45);          // Displaying the Stack         System.out.println("The stack is: " + STACK);          // Initialize Sum Variable which will store sum of         // all element         int sum = 0;         // Popping till Stack is Not Empty         while (!STACK.empty()) {             /* If stack have some elements then              Stack.empty() will written false and ! of it              will true so while will till !STACK.empty() it              become false for this to be false STACK.empty()              need to be true when STACK.empty() is true mean              we have completely travel Stack*/             sum += STACK.pop();         }         // Initialize         System.out.println("The Sum Of Elements is " + sum);          // Checking for the emptiness of stack         System.out.println("Is the stack empty? "                            + STACK.empty());     }       // This Code is Contributed By Vikas Bishnoi } 

Output
The stack is: [23, 3, -30, 13, 45] The Sum Of Elements is 54 Is the stack empty? true

Program 4 : Use java.util.Stack.empty() method to implement error handling in program. 

For example, if you are reading data from a file into a stack, you can check if the stack is empty after reading the data to ensure that the file is not empty.

Java
// Java code to demonstrate error handling using empty() method  import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Stack;  public class FileReadExample {      public static void main(String[] args) {         Stack<String> stack = new Stack<>();          // read data from file         try {             File file = new File("data.txt");             Scanner scanner = new Scanner(file);             while (scanner.hasNextLine()) {                 String line = scanner.nextLine();                 stack.push(line);             }             scanner.close();         } catch (FileNotFoundException e) {             System.out.println("File not found.");         }          // check if stack is empty         if (stack.empty()) {             System.out.println("File is empty.");         } else {             System.out.println("File is not empty. Stack contents:");             while (!stack.empty()) {                 System.out.println(stack.pop());             }         }     }  }  // This code is contributed by vishalkumarsahu04 

Time Complexity: O(n), where n is the number of lines in the file.
Space Complexity : O(n), where n is the number of lines in the file.


Next Article
Stack search() Method in Java

C

chinmoy lenka
Improve
Article Tags :
  • Misc
  • Java
  • Java-Collections
  • Java - util package
  • Java-Functions
  • Java-Stack
Practice Tags :
  • Java
  • Java-Collections
  • Misc

Similar Reads

    Stack Class in Java
    The Java Collection framework provides a Stack class, which implements a Stack data structure. The class is based on the basic principle of LIFO (last-in-first-out). Besides the basic push and pop operations, the class also provides three more functions, such as empty, search, and peek. The Stack cl
    11 min read
    Stack push() Method in Java
    Java.util.Stack.push(E element) method is used to push an element into the Stack. The element gets pushed onto the top of the Stack. Syntax: STACK.push(E element)Parameters: The method accepts one parameter element of type Stack and refers to the element to be pushed into the stack. Return Value: Th
    2 min read
    Stack pop() Method in Java
    The Java.util.Stack.pop() method in Java is used to pop an element from the stack. The element is popped from the top of the stack and is removed from the same.Syntax: STACK.pop() Parameters: The method does not take any parameters.Return Value: This method returns the element present at the top of
    2 min read
    Stack peek() Method in Java
    The java.util.Stack.peek() method in Java is used to retrieve or fetch the first element of the Stack or the element present at the top of the Stack. The element retrieved does not get deleted or removed from the Stack. Syntax:STACK.peek()Parameters: The method does not take any parameters. Return V
    2 min read
    Stack empty() Method in Java
    The java.util.Stack.empty() method in Java is used to check whether a stack is empty or not. The method is of boolean type and returns true if the stack is empty else false. Syntax: STACK.empty() Parameters: The method does not take any parameters. Return Value: The method returns boolean true if th
    4 min read
    Stack search() Method in Java
    The java.util.Stack.search(Object element) method in Java is used to search for an element in the stack and get its distance from the top. This method starts the count of the position from 1 and not from 0. The element that is on the top of the stack is considered to be at position 1. If more than o
    2 min read
    Stack removeElementAt() method in Java with Example
    The Java.util.Stack.removeElementAt(int index) method is used to remove an element from a Stack from a specific position or index. In this process the size of the Stack is automatically reduced by one and all other elements after the removed element are shifted downwards by one position. Syntax: Sta
    2 min read
    Stack remove(int) method in Java with Example
    The Java.util.Stack.remove(int index) method is used to remove an element from a Stack from a specific position or index. Syntax: Stack.remove(int index) Parameters: This method accepts a mandatory parameter index is of integer data type and specifies the position of the element to be removed from t
    2 min read
    Stack removeAllElements() method in Java with Example
    The Java.util.Stack.removeAllElements() method is used to removes all components from this Stack and sets its size to zero. Syntax: Stack.removeAllElements() Parameters: The method does not take any parameter Return Value: The function does not returns any value. Below programs illustrate the Java.u
    2 min read
    Stack remove(Object) method in Java with Example
    The Java.util.Stack.remove(Object o) method is used to remove any particular element from the Stack. Syntax: Stack.remove(Object o) Parameters: This method accepts a mandatory parameter o is of the object type of Stack and specifies the element to be removed from the Stack. Return Value: Returns Tru
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences