What is the Stack.empty method in Java?
The empty method of the Stack class checks if the stack object contains an element.
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
Syntax
public boolean empty();
Return Value
If the stack object is empty, the method returns true. Otherwise, it returns false.
Code
import java.util.Stack;class StackIsEmptyExample {public static void main( String args[] ) {// Creating StackStack<Integer> stack = new Stack<>();// Print StackSystem.out.println("The Stack is: " + stack);System.out.println("Is Stack Empty: " + stack.isEmpty());// add elememtsstack.push(1);// Print StackSystem.out.println("The Stack is: " + stack);System.out.println("Is Stack Empty: " + stack.isEmpty());}}
Explanation
In this example, we create a stack object. Initially, the stack object doesn’t contain any elements, so the empty method will return true when we call stack.empty().
We then added one element to the stack object using the push method. Now when we call the empty method, false is returned because the stack object is not empty.