Java Stack
Stack is a legacy Java collection class used to implement a Last In, First Out (LIFO) data structure.
LIFO means that the element added most recently is removed first.
A simple real-world example is a stack of plates:
┌─────────┐
│ Plate 3 │ ← Added last / removed first
├─────────┤
│ Plate 2 │
├─────────┤
│ Plate 1 │ ← Added first
└─────────┘In Java:
Stack<String> stack = new Stack<>();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack);Output
[A, B, C]The top element is C.
Why Use a Stack?
A stack is useful when the most recently added item needs to be processed first.
Common examples include:
- Undo operations
- Backtracking
- Expression processing
- Navigation history
- Depth-first traversal
- Temporary processing of nested operations
Creating a Stack
Import the class:
import java.util.Stack;Create an object:
Stack<String> stack = new Stack<>();Adding Elements Using push()
The push() method adds an element to the top of the stack.
stack.push("Java");
stack.push("Python");
stack.push("C++");The stack becomes:
C++
Python
JavaC++ is the top element.
Removing Elements Using pop()
The pop() method removes and returns the element at the top.
String language = stack.pop();
System.out.println(language);Output
C++The remaining stack is:
Python
JavaReading the Top Element Using peek()
peek() returns the top element without removing it.
String top = stack.peek();
System.out.println(top);If the stack contains:
C++
Python
Javapeek() returns:
C++The stack remains unchanged.
Checking Whether the Stack Is Empty
Use:
stack.empty();Example
if (stack.empty()) {
System.out.println("Stack is empty");
}isEmpty() can also be used because Stack inherits collection methods.
stack.isEmpty();Searching the Stack
search() returns the position of an element measured from the top of the stack.
Stack<String> stack = new Stack<>();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack.search("C"));
System.out.println(stack.search("A"));Output
1
3Because C is at the top, its position is 1.
Stack Follows LIFO
Consider:
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);The stack is:
30 ← Top
20
10Now:
System.out.println(stack.pop());Output
30Then:
System.out.println(stack.pop());Output
20Then:
System.out.println(stack.pop());Output
10So the order is:
10 → 20 → 30Removal:
30 → 20 → 10Complete Example
import java.util.Stack;
public class HelloWorld {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Java");
stack.push("Python");
stack.push("C++");
System.out.println("Stack: " + stack);
System.out.println("Top: " + stack.peek());
System.out.println("Removed: " + stack.pop());
System.out.println("Stack after pop: " + stack);
}
}Output
Stack: [Java, Python, C++]
Top: C++
Removed: C++
Stack after pop: [Java, Python]Stack and Deque
Although Java provides Stack, modern Java code often uses Deque when stack behavior is required.
For example:
Deque<String> stack = new ArrayDeque<>();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack.pop());Output
CThis provides stack behavior without using the legacy Stack class.
Stack vs Queue
| Feature | Stack | Queue |
|---|---|---|
| Principle | LIFO | FIFO is common; implementation dependent |
| First processed | Last added | First added for FIFO queues |
| Add operation | push() | offer() |
| Remove operation | pop() | poll() |
| Read next element | peek() | peek() |
| Example | Undo history | Customer waiting line |
Stack vs ArrayDeque
| Feature | Stack | ArrayDeque |
|---|---|---|
| Purpose | Stack | Queue/Deque/Stack |
| Legacy class | Yes | No |
| Stack operations | Yes | Yes |
| Typical modern choice for stack behavior | Less common | Common |
| Null elements | Permitted | Not permitted |
What Happens When pop() Is Called on an Empty Stack?
Calling:
stack.pop();when the stack is empty causes:
EmptyStackExceptionTherefore, you can check first:
if (!stack.empty()) {
System.out.println(stack.pop());
}Important Points
- Stack follows the LIFO principle.
- push() adds an element.
pop() removes the top element. peek() reads the top element without removing it. empty() checks whether the stack contains elements. search() searches from the top of the stack. Stack extends Vector. Stack is a legacy collection class. For new code, Deque with ArrayDeque is generally preferred for stack behavior.
Key Takeaway
A stack is a Last In, First Out (LIFO) data structure. Java's Stack class provides operations such as push(), pop(), and peek(). Although Stack is still available and commonly encountered in existing code, Deque with ArrayDeque is generally the preferred approach when implementing a stack in modern Java.
See you in next page....🙂