A stack is a way of storing items where you can only add and remove at one end, called the top. The last item you put in is the first item you take out. This rule is called LIFO: Last In, First Out.
This page uses a pile of plates to explain the idea, then walks through push, pop and peek, and ends with a small Java program you can run. If data structures are new to you, read what are data structures first.
Stack in simple words: the plate analogy
Think of the pile of clean plates at a hostel mess or a wedding buffet.
- When a plate is washed, it goes on top of the pile.
- When someone needs a plate, they take the one on top.
- Nobody pulls a plate from the middle or the bottom.
The plate that was placed last is picked first. That is exactly how a stack works.
| At the plate pile | In a stack |
|---|---|
| Put a plate on top | push |
| Take the top plate | pop |
| Look at the top plate without taking it | peek |
| No plates left | The stack is empty |
| No room on the shelf for more plates | The stack is full (only for fixed-size stacks) |
LIFO explained with a picture
Here is a stack after pushing 10, then 20, then 30:
top -> | 30 |
| 20 |
| 10 |
+----+
30 went in last, so it sits on top and will come out first. To reach 10, you must first pop 30 and 20.
The opposite rule is FIFO (First In, First Out), used by a queue, where the oldest item leaves first. Our queue data structure guide covers it, and stack vs queue puts the two side by side.
Stack operations: push, pop and peek
| Operation | What it does | Time |
|---|---|---|
push(x) |
Adds x on top |
O(1) |
pop() |
Removes the top item and returns it | O(1) |
peek() |
Returns the top item without removing it | O(1) |
isEmpty() |
Tells you if the stack has no items | O(1) |
size() |
Number of items | O(1) |
All the main operations take the same short time no matter how many items the stack holds, because you only ever touch the top.
Push and pop step by step
Start: (empty)
push(10): [10] top = 10
push(20): [10, 20] top = 20
push(30): [10, 20, 30] top = 30
pop(): [10, 20] returns 30
peek(): [10, 20] returns 20, nothing removed
pop(): [10] returns 20
Read the lists left to right as bottom to top.
Overflow and underflow
- Stack overflow: you try to push onto a stack that is already full. This happens with a fixed-size array stack.
- Stack underflow: you try to pop or peek on an empty stack.
Good code checks for both. You will see these checks in the Java example below.
A small stack in Java
This program builds a stack on a fixed-size array. The variable top holds the index of the top item. It starts at -1, which means the stack is empty.
public class StackDemo {
static int[] items = new int[5];
static int top = -1;
static void push(int value) {
if (top == items.length - 1) {
System.out.println("Stack is full, cannot push " + value);
return;
}
top++;
items[top] = value;
}
static int pop() {
if (top == -1) {
System.out.println("Stack is empty");
return -1;
}
int value = items[top];
top--;
return value;
}
static int peek() {
if (top == -1) {
System.out.println("Stack is empty");
return -1;
}
return items[top];
}
static boolean isEmpty() {
return top == -1;
}
public static void main(String[] args) {
push(10);
push(20);
push(30);
System.out.println("Top item: " + peek());
System.out.println("Popped: " + pop());
System.out.println("Popped: " + pop());
System.out.println("Top item now: " + peek());
System.out.println("Empty? " + isEmpty());
pop();
System.out.println("Empty? " + isEmpty());
pop();
}
}
Output:
Top item: 30
Popped: 30
Popped: 20
Top item now: 10
Empty? false
Empty? true
Stack is empty
Save it as StackDemo.java and run java StackDemo.java with Java 11 or later.
How it works:
pushmovestopup by one, then stores the value there.popreads the value attop, then movestopdown by one. The old value is still in the array, but it no longer counts as part of the stack.- The last
pop()call findstop == -1and prints "Stack is empty". That is underflow being handled.
Common mistake: Writing
items[top] = value; top++;inpush. Withtopstarting at -1, the very first push tries to write toitems[-1]and Java throwsArrayIndexOutOfBoundsException. Increasetopfirst, then store.
A stack can also be built on a linked list. Push and pop then become "add at head" and "remove head", and the stack has no fixed size.
Using a stack from the Java library
At work, you use the built-in classes. In Java, the recommended choice is ArrayDeque through the Deque interface:
import java.util.ArrayDeque;
import java.util.Deque;
public class BuiltInStack {
public static void main(String[] args) {
Deque<String> plates = new ArrayDeque<>();
plates.push("Red");
plates.push("Blue");
plates.push("Green");
System.out.println(plates);
System.out.println("Top: " + plates.peek());
System.out.println("Removed: " + plates.pop());
System.out.println(plates + " size " + plates.size());
}
}
Output:
[Green, Blue, Red]
Top: Green
Removed: Green
[Blue, Red] size 2
Notice that printing the deque shows the top item first. Java also has an older java.util.Stack class. It still works, but its methods are synchronized, which makes it slower, and the Java documentation suggests Deque instead.
A real stack example: checking brackets
Code editors and compilers check whether brackets are balanced. A stack makes this easy:
- Read the text one character at a time.
- When you see an opening bracket, push it.
- When you see a closing bracket, pop and check that it matches.
- At the end, the stack must be empty.
import java.util.ArrayDeque;
import java.util.Deque;
public class BracketCheck {
static boolean isBalanced(String text) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : text.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (stack.isEmpty()) return false;
char open = stack.pop();
if ((c == ')' && open != '(') ||
(c == ']' && open != '[') ||
(c == '}' && open != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(isBalanced("{[()]}"));
System.out.println(isBalanced("([)]"));
System.out.println(isBalanced("(()"));
}
}
Output:
true
false
false
([)] fails because ) arrives when [ is on top. (() fails because one ( is still left on the stack at the end. This "valid parentheses" problem is one of the most common stack questions in placement tests.
Where stacks are used
- Undo in editors: each change is pushed; Ctrl+Z pops the latest one.
- Browser back button: each page you visit is pushed; Back pops the current page.
- Function calls: when a method calls another method, the program keeps a call stack. If a recursive function never stops, the call stack fills up and Java throws
StackOverflowError. - Bracket checking in compilers and code editors, as shown above.
- Expression evaluation: calculators use stacks to evaluate expressions such as
3 + 4 * 2. - Depth-first search (DFS) in graphs and trees uses a stack, either your own or the call stack.
Stack vs queue in one table
| Point | Stack | Queue |
|---|---|---|
| Rule | LIFO, last in first out | FIFO, first in first out |
| Add | push, at the top | enqueue, at the rear |
| Remove | pop, from the top | dequeue, from the front |
| Everyday example | Pile of plates | Ticket counter line |
| Java choice | ArrayDeque with push/pop |
ArrayDeque with offer/poll |
For more differences and interview angles, read stack vs queue.
Practice problems for beginners
Try these in order. Draw the stack on paper after each push and pop.
- Reverse a string using a stack.
- Check if brackets in a string are balanced.
- Build a stack that can also return the minimum value in O(1).
- Evaluate a postfix expression such as
2 3 4 * +(answer: 14). - Find the next greater element for each value in an array.
Quick revision
- A stack adds and removes only at the top.
- It follows LIFO: last in, first out.
- push adds, pop removes, peek looks. All are O(1).
- Overflow is pushing onto a full stack; underflow is popping an empty one.
- In Java, use
Deque<T> stack = new ArrayDeque<>().
Once push and pop feel natural, learn the queue data structure, then move on with our data structures and algorithms guide and the DSA interview questions.
Frequently Asked Questions
What is a stack in simple words?
What does LIFO mean?
What are push and pop?
What is stack overflow and stack underflow?
Which class should I use for a stack in Java?
What is the difference between a stack and a queue?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — Explore the Java Full Stack program

