1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Stack Implementation
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
20Hrs
35Mins
04Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Stack Implementation

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
20Hrs
35Mins
04Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Stack

Overview

A Stack is a linear data structure that strictly follows the LIFO (Last-In, First-Out) principle. Think of it like a physical stack of plates in a cafeteria: you can only add a new plate to the top of the stack, and you can only take a plate off the top of the stack. The last plate placed is the first one removed.

The core operations of a Stack are Push (add to top), Pop (remove from top), and Peek (look at the top without removing). All three operations must execute in strict O(1) time.

Stacks are not just abstract concepts; they are the fundamental mechanism powering modern computing. Every time a Java method is called, a new 'frame' is pushed onto the JVM's Call Stack. When the method returns, its frame is popped off. Stacks are also the core data structure used in Depth-First Search (DFS) algorithms, expression evaluation, and undo/redo mechanics.

Syntax

While Java has a java.util.Stack class, it extends Vector and is synchronized, making it unnecessarily slow. The official Java documentation recommends using ArrayDeque when you need a stack.

Using Java's Deque as a Stack
java
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        // NOTE: In modern Java, ArrayDeque is preferred over the legacy Stack class!
        Deque<String> stack = new ArrayDeque<>();
        
        // 1. Push (Add to top) - O(1)
        stack.push("First");
        stack.push("Second");
        stack.push("Third");
        
        // 2. Peek (View top without removing) - O(1)
        System.out.println("Top is: " + stack.peek()); // "Third"
        
        // 3. Pop (Remove and return top) - O(1)
        String removed = stack.pop(); 
        System.out.println("Removed: " + removed); // "Third"
        
        // 4. Check if empty
        while (!stack.isEmpty()) {
            System.out.println("Popping: " + stack.pop());
        }
        // Output: "Second", then "First"
    }
}

Common Pitfalls

  • Using the legacy java.util.Stack class. It was introduced in Java 1.0 and every single method is synchronized, causing thread-locking overhead even in single-threaded apps. Always use Deque<T> stack = new ArrayDeque<>() instead.
  • Calling pop() or peek() on an empty stack. This will throw a NoSuchElementException (or EmptyStackException). Always wrap pops inside a while(!stack.isEmpty()) check, or explicitly check isEmpty() before peeking.
  • Confusing add() with push(). While ArrayDeque supports both, push() adds to the front (top) of the deque, while add() adds to the back (tail). Mixing them up will turn your Stack into a Queue!

Interview Questions

How would you implement a Stack using only Queues?

Use two Queues (q1 and q2). For push(x), enqueue x to q2. Then dequeue all elements from q1 and enqueue them to q2. Finally, swap the names of q1 and q2. This makes push O(N) and pop O(1). Alternatively, you can do it with one Queue by enqueuing x, then dequeuing and re-enqueuing all the other elements behind it.

What is a StackOverflowError in Java?

It occurs when the JVM's Call Stack exceeds its memory limit. Every method call pushes a frame (containing local variables and return addresses) to the call stack. If a recursive method lacks a base case, it will call itself infinitely, pushing frames until the memory allocated for the thread's stack is completely exhausted.

Why is an Array-backed Stack (like ArrayDeque) generally faster than a Linked-List-backed Stack?

Cache locality. Arrays store data contiguously in memory, which the CPU cache can pre-fetch highly efficiently. Linked List nodes are scattered across the heap, causing CPU cache misses. Additionally, Linked Lists have the overhead of instantiating a new Node object for every single push operation.

Real-World Example

Text editors use two Stacks to implement the Undo and Redo features. When you type, actions are pushed to the Undo stack. When you hit Ctrl+Z, the action is popped from the Undo stack and pushed to the Redo stack. If you type something new, the Redo stack is cleared.

example
java
Deque<String> undoStack = new ArrayDeque<>();
Deque<String> redoStack = new ArrayDeque<>();

public void typeText(String text) {
    undoStack.push(text);
    redoStack.clear(); // Typing clears redo history
}

public void undo() {
    if (!undoStack.isEmpty()) {
        String action = undoStack.pop();
        redoStack.push(action);
        // revert action in UI...
    }
}

public void redo() {
    if (!redoStack.isEmpty()) {
        String action = redoStack.pop();
        undoStack.push(action);
        // apply action in UI...
    }
}

Check Your Knowledge

Test your understanding of Stack with these quick questions.

Question 1

Which principle governs how a Stack operates?

Question 2

What is the recommended Java class to use when you need a Stack?

Question 3

What is the time complexity of the `push()` and `pop()` operations?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Stack

Overview

A Stack is a linear data structure that strictly follows the LIFO (Last-In, First-Out) principle. Think of it like a physical stack of plates in a cafeteria: you can only add a new plate to the top of the stack, and you can only take a plate off the top of the stack. The last plate placed is the first one removed.

The core operations of a Stack are Push (add to top), Pop (remove from top), and Peek (look at the top without removing). All three operations must execute in strict O(1) time.

Stacks are not just abstract concepts; they are the fundamental mechanism powering modern computing. Every time a Java method is called, a new 'frame' is pushed onto the JVM's Call Stack. When the method returns, its frame is popped off. Stacks are also the core data structure used in Depth-First Search (DFS) algorithms, expression evaluation, and undo/redo mechanics.

Syntax

While Java has a java.util.Stack class, it extends Vector and is synchronized, making it unnecessarily slow. The official Java documentation recommends using ArrayDeque when you need a stack.

Using Java's Deque as a Stack
java
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        // NOTE: In modern Java, ArrayDeque is preferred over the legacy Stack class!
        Deque<String> stack = new ArrayDeque<>();
        
        // 1. Push (Add to top) - O(1)
        stack.push("First");
        stack.push("Second");
        stack.push("Third");
        
        // 2. Peek (View top without removing) - O(1)
        System.out.println("Top is: " + stack.peek()); // "Third"
        
        // 3. Pop (Remove and return top) - O(1)
        String removed = stack.pop(); 
        System.out.println("Removed: " + removed); // "Third"
        
        // 4. Check if empty
        while (!stack.isEmpty()) {
            System.out.println("Popping: " + stack.pop());
        }
        // Output: "Second", then "First"
    }
}

Common Pitfalls

  • Using the legacy java.util.Stack class. It was introduced in Java 1.0 and every single method is synchronized, causing thread-locking overhead even in single-threaded apps. Always use Deque<T> stack = new ArrayDeque<>() instead.
  • Calling pop() or peek() on an empty stack. This will throw a NoSuchElementException (or EmptyStackException). Always wrap pops inside a while(!stack.isEmpty()) check, or explicitly check isEmpty() before peeking.
  • Confusing add() with push(). While ArrayDeque supports both, push() adds to the front (top) of the deque, while add() adds to the back (tail). Mixing them up will turn your Stack into a Queue!

Interview Questions

How would you implement a Stack using only Queues?

Use two Queues (q1 and q2). For push(x), enqueue x to q2. Then dequeue all elements from q1 and enqueue them to q2. Finally, swap the names of q1 and q2. This makes push O(N) and pop O(1). Alternatively, you can do it with one Queue by enqueuing x, then dequeuing and re-enqueuing all the other elements behind it.

What is a StackOverflowError in Java?

It occurs when the JVM's Call Stack exceeds its memory limit. Every method call pushes a frame (containing local variables and return addresses) to the call stack. If a recursive method lacks a base case, it will call itself infinitely, pushing frames until the memory allocated for the thread's stack is completely exhausted.

Why is an Array-backed Stack (like ArrayDeque) generally faster than a Linked-List-backed Stack?

Cache locality. Arrays store data contiguously in memory, which the CPU cache can pre-fetch highly efficiently. Linked List nodes are scattered across the heap, causing CPU cache misses. Additionally, Linked Lists have the overhead of instantiating a new Node object for every single push operation.

Real-World Example

Text editors use two Stacks to implement the Undo and Redo features. When you type, actions are pushed to the Undo stack. When you hit Ctrl+Z, the action is popped from the Undo stack and pushed to the Redo stack. If you type something new, the Redo stack is cleared.

example
java
Deque<String> undoStack = new ArrayDeque<>();
Deque<String> redoStack = new ArrayDeque<>();

public void typeText(String text) {
    undoStack.push(text);
    redoStack.clear(); // Typing clears redo history
}

public void undo() {
    if (!undoStack.isEmpty()) {
        String action = undoStack.pop();
        redoStack.push(action);
        // revert action in UI...
    }
}

public void redo() {
    if (!redoStack.isEmpty()) {
        String action = redoStack.pop();
        undoStack.push(action);
        // apply action in UI...
    }
}

Check Your Knowledge

Test your understanding of Stack with these quick questions.

Question 1

Which principle governs how a Stack operates?

Question 2

What is the recommended Java class to use when you need a Stack?

Question 3

What is the time complexity of the `push()` and `pop()` operations?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A