Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

stack
empty
java
communitycreator

What is the Stack.empty method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

stack
empty
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring