What is stack.empty() in Java?

The stack.empty() function in Java returns true if the stack is empty; otherwise, it returns false. In short, this function is used to check if the stack is empty or not.

The image below shows the visual representation of the stack.empty() function.

Visual representation of stack.empty() function

The java.util.* module is required in order to use this function.

Syntax

stack_name.empty();
// where the stack_name is the name of the stack

Parameters

The stack.empty() function does not require any parameters.

Return value

If the stack is empty, the stack.empty() function returns true. Otherwise, it returns false.

Code

import java.util.*;
class JAVA {
public static void main( String args[] ) {
Stack<Integer> Stack1 = new Stack<Integer>();
//filled stack
Stack1.add(0);
Stack1.add(2);
Stack1.add(5);
Stack1.add(3);
Stack1.add(1);
System.out.println("Stack1 is empty: " + Stack1.empty());
//empty stack
Stack<Integer> Stack2 = new Stack<Integer>();
System.out.println("Stack2 is empty: " + Stack2.empty());
}
}

Free Resources