The empty
method of the Stack
class checks if the stack
object contains an element.
The
Stack
class is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
public boolean empty();
If the stack
object is empty, the method returns true
. Otherwise, it returns false
.
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());}}
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.