Java Utility Library

Java Stack - empty() Method



The java.util.Stack.empty() method is used to check whether the stack is empty or not. It returns true if the size of the stack is zero, else returns false.

Syntax

public boolean empty()

Parameters

No parameter is required.

Return Value

true if the stack is empty, else returns false.

Exception

NA

Example:

In the example below, the java.util.Stack.empty() method is used to check whether the stack is empty or not.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<String> MyStack = new Stack<String>();

    //checking stack
    System.out.println("Is MyStack empty?: " + MyStack.empty());

    //populating stack
    MyStack.push("Alpha");
    MyStack.push("Coding");
    MyStack.push("Skills");

    //checking stack
    System.out.println("Is MyStack empty?: " + MyStack.empty());
  }
}

The output of the above code will be:

Is MyStack empty?: true
Is MyStack empty?: false

❮ Java.util - Stack