The Wayback Machine - https://web.archive.org/web/20240618020138/https://www.geeksforgeeks.org/stack-empty-method-in-java/
Open In App

Stack empty() Method in Java

Last Updated : 24 May, 2023
Improve
Improve
Like Article
Like
Save
Share
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.



Previous Article
Next Article

Similar Reads

Java Program to Empty an ArrayList in Java
ArrayList class is a resizable array, present in 'java.util package'. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an Arra
3 min read
OptionalLong empty() method in Java with examples
OptionalLong help us to create an object which may or may not contain a Long value. The empty() method returns an empty OptionalLong instance. No value is present for this OptionalLong. So we can say that this method help us to create empty OptionalLong object. Syntax: public static OptionalLong empty() Parameters: This method accepts nothing. Retu
1 min read
OptionalDouble empty() method in Java with examples
OptionalDouble help us to create an object which may or may not contain a Double value. The empty() method returns an empty OptionalDouble instance. No value is present for this OptionalDouble. So we can say that this method help us to create empty OptionalDouble object. Syntax: public static OptionalDouble empty() Parameters: This method accepts n
1 min read
OptionalInt empty() method in Java with examples
OptionalInt help us to create an object which may or may not contain a int value. The empty() method returns an empty OptionalInt instance. No value is present for this OptionalInt. So we can say that this method help us to create empty OptionalInt object. Syntax: public static OptionalInt empty() Parameters: This method accepts nothing.Return valu
1 min read
Optional empty() method in Java with examples
The empty() method of java.util.Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value. Syntax: public static &lt;T&gt; Optional&lt;T&gt; empty() Parameters: This method accepts nothing. Return value: This method returns an empty instance of this Optional class. Below programs illustra
1 min read
IntStream empty() in Java with examples
IntStream empty() is a method in java.util.stream.IntStream. This method returns an empty sequential IntStream. Syntax : static &lt;T&gt; Stream&lt;T&gt; empty() Where, T is the type of stream elements, and the function returns an empty sequential stream. Example 1 : Creating empty IntStream. // Java code for IntStream empty() import java.util.*; i
1 min read
Program to check if the String is Empty in Java
Given a string str, the task is to check if this string is empty or not, in Java. Examples: Input: str = "" Output: True Input: str = "GFG" Output: False Approach 1: Get the String to be checked in strWe can simply check if the string is empty or not using the isEmpty() method of String class Syntax:if (str.isEmpty())Print true if the above conditi
2 min read
Java Program to Check if a Directory is Empty or Not
The list() method defined in class java.io.File which is used to obtain the list of files and folders(directories) present in the specified directory defined by its pathname. The list of files is stored in an array of string. If the length of an array is greater than 0, then the specified directory is not empty, else it is empty. Method 1: Use of l
3 min read
Creating an Empty PDF Document using Java
For creating a PDF document using Java, we need to know the packages/libraries which are necessary for writing the code. So, for creating a PDF doc, we will be using the iText 7 library. To know how to install this library in your workspace, you can follow this link. Creating An Empty PDF Doc To create an empty PDF Document, we first need to instan
3 min read
How to Copy and Add all List Elements to an Empty ArrayList in Java?
We can copy and add List items in Array List using addAll() method. This method accepts a Collection (Ex. List) as an argument and adds the collection items at the end of its calling Collection (Ex. ArrayList). This method returns a boolean value. addAll() return true if the collection successfully adds else it returns false. We can clone the list
2 min read