What is the Stack.empty method in Java?

The empty method of the Stack class checks if the stack object contains an element.

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

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 Stack
Stack<Integer> stack = new Stack<>();
// Print Stack
System.out.println("The Stack is: " + stack);
System.out.println("Is Stack Empty: " + stack.isEmpty());
// add elememts
stack.push(1);
// Print Stack
System.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.

Free Resources