1. Java Stack class

In Java Stack class is a child class of Vector class in collection framework.

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack.

Java Stack data structure:

Java Stack data structure

When to use Stack in Java? : Whenever last in first out order required then we should go for Stack in Java.

Hierarchy of Java Stack class:

Java Stack class hierarchy

2. Java Stack class methods

  1. Object push(Object element) : push() method use to push an item onto the top of the stack.
  2. Object pop() : pop() method use to remove the object at the top of the stack and returns that object as the value.
  3. Object peek() : peek() method use to looks at the object at the top of this stack without removing it from the stack.
  4. boolean empty() : It returns true if nothing is on the top of the stack. Else, returns false.
  5. int search(Object element) : search() method returns position of the element if element is exist, otherwise returns -1. This method can used to determine an element in the stack exist or not.

3. Demonstrating Java Stack class methods

Copy to Clipboard

Output

Copy to Clipboard