What is a stack class in Java?
In Java, a stack class is a part of the Java Collections Framework that implements a Last-In-First-Out (LIFO) data structure. It’s a subclass of the Vector class and is used to store and manipulate a collection of objects.
A Stack is a dynamic array that follows the LIFO principle, meaning that the last element added to the stack (pushed) is the first to be removed (popped). This makes it useful for implementing recursive algorithms, parsing expressions, and evaluating postfix notation, among other applications.
The Stack class in Java provides several methods for manipulating the stack, including:
- push(E item): Adds an element to the top of the stack.
- pop(): Removes and returns the top element from the stack.
- peek(): Returns the top element from the stack without removing it.
- empty(): Checks if the stack is empty.
- search(Object o): Searches for an element in the stack and returns its position (1-based index).
The peek-and-pop methods in a Java Stack class are similar, but they have a key difference:
Get Mayanknegi’s stories in your inbox
Join Medium for free to get updates from this writer.
peek():
- Returns the top element from the stack without removing it.
- The element is still present in the stack after calling peek().
- If the stack is empty, it throws an EmptyStackException.
pop():
- Removes and returns the top element from the stack.
- The element is removed from the stack after calling pop().
- If the stack is empty, it throws an EmptyStackException.








