Bird
Raised Fist0
DSA Javaprogramming

Peek Top Element of Stack in DSA Java

Choose your learning style10 modes available
Mental Model
A stack is like a pile of plates where you only see and use the top plate. Peeking means looking at the top plate without removing it.
Analogy: Imagine a stack of books on a table. You can only see and touch the top book. Peeking is just looking at the top book's cover without taking it off the stack.
Stack top
  ↑
+-----+
|  3  |  ← top
+-----+
|  2  |
+-----+
|  1  |
+-----+
null
Dry Run Walkthrough
Input: stack: push 1, push 2, push 3; peek top element
Goal: Find the value of the top element without removing it
Step 1: push 1 onto empty stack
Stack top
  ↑
+-----+
|  1  |  ← top
+-----+
null
Why: We start with an empty stack and add the first element
Step 2: push 2 onto stack
Stack top
  ↑
+-----+
|  2  |  ← top
+-----+
|  1  |
+-----+
null
Why: New element goes on top, previous top moves down
Step 3: push 3 onto stack
Stack top
  ↑
+-----+
|  3  |  ← top
+-----+
|  2  |
+-----+
|  1  |
+-----+
null
Why: Again, new element becomes the top
Step 4: peek top element
Stack top
  ↑
+-----+
|  3  |  ← top
+-----+
|  2  |
+-----+
|  1  |
+-----+
null
Why: Peeking shows the top value without changing the stack
Result:
Stack top
  ↑
+-----+
|  3  |  ← top
+-----+
|  2  |
+-----+
|  1  |
+-----+
null
Peeked value: 3
Annotated Code
DSA Java
import java.util.EmptyStackException;

class Stack {
    private int[] arr;
    private int top;
    private int capacity;

    public Stack(int size) {
        arr = new int[size];
        capacity = size;
        top = -1; // stack is empty
    }

    public void push(int x) {
        if (top == capacity - 1) {
            throw new RuntimeException("Stack Overflow");
        }
        arr[++top] = x; // place element on top
    }

    public int peek() {
        if (top == -1) {
            throw new EmptyStackException(); // stack empty
        }
        return arr[top]; // return top element without removing
    }

    public String toString() {
        if (top == -1) return "Stack is empty";
        StringBuilder sb = new StringBuilder();
        sb.append("Stack top\n  ↑\n");
        for (int i = top; i >= 0; i--) {
            sb.append("+-----+\n|  ").append(arr[i]).append("  |  ");
            if (i == top) sb.append("← top");
            sb.append("\n+-----+\n");
        }
        sb.append("null");
        return sb.toString();
    }
}

public class PeekTopElementOfStack {
    public static void main(String[] args) {
        Stack stack = new Stack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.toString());
        int topValue = stack.peek();
        System.out.println("Peeked value: " + topValue);
    }
}
arr[++top] = x; // place element on top
increment top index and place new element there
if (top == -1) { throw new EmptyStackException(); }
check if stack is empty before peeking
return arr[top]; // return top element without removing
return the current top element without changing stack
OutputSuccess
Stack top ↑ +-----+ | 3 | ← top +-----+ | 2 | +-----+ | 1 | +-----+ null Peeked value: 3
Complexity Analysis
Time: O(1) because peek just reads the top element without traversal
Space: O(n) because stack stores up to n elements in an array
vs Alternative: Compared to popping, peek does not remove elements so it is faster and safer when only viewing is needed
Edge Cases
empty stack
throws EmptyStackException to signal no elements to peek
DSA Java
if (top == -1) { throw new EmptyStackException(); }
stack with one element
peek returns that single element correctly
DSA Java
return arr[top];
When to Use This Pattern
When you need to see the last added item without removing it, use the peek operation on a stack to get that value instantly.
Common Mistakes
Mistake: Trying to peek when the stack is empty without checking causes errors.
Fix: Always check if the stack is empty before peeking and handle that case properly.
Mistake: Modifying the stack (like popping) instead of just peeking when only viewing is needed.
Fix: Use peek to view the top element without changing the stack.
Summary
Peek returns the top element of the stack without removing it.
Use peek when you want to see the last added item but keep it in the stack.
The key insight is that peek looks at the top without changing the stack's content.

Practice

(1/5)
1. What does the peek() method do in a stack?
easy
A. Checks if the stack is empty
B. Removes and returns the top element
C. Adds a new element to the top
D. Returns the top element without removing it

Solution

  1. Step 1: Understand the peek method purpose

    The peek method is designed to look at the top element of the stack without changing the stack.
  2. Step 2: Compare with other stack methods

    Unlike pop, peek does not remove the element; it only returns it.
  3. Final Answer:

    Returns the top element without removing it -> Option D
  4. Quick Check:

    peek() = top element without removal [OK]
Hint: Peek shows top without removing it [OK]
Common Mistakes:
  • Confusing peek with pop
  • Thinking peek adds elements
  • Assuming peek checks emptiness
2. Which of the following is the correct syntax to peek the top element of a Java Stack named stack?
easy
A. stack.peek();
B. stack.top();
C. stack.getTop();
D. stack.pop();

Solution

  1. Step 1: Recall Java Stack method names

    The Java Stack class uses peek() to view the top element without removing it.
  2. Step 2: Check other options for correctness

    top() and getTop() are not valid Stack methods; pop() removes the top element.
  3. Final Answer:

    stack.peek(); -> Option A
  4. Quick Check:

    Correct syntax for peek is stack.peek() [OK]
Hint: Use stack.peek() to view top element [OK]
Common Mistakes:
  • Using pop() instead of peek()
  • Using non-existent methods like top()
  • Missing parentheses in method call
3. What will be the output of the following Java code?
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.peek());
medium
A. 10
B. 30
C. 20
D. StackEmptyException

Solution

  1. Step 1: Trace the push operations

    Elements pushed in order: 10 (bottom), 20, then 30 (top).
  2. Step 2: Understand peek output

    peek() returns the top element without removing it, which is 30.
  3. Final Answer:

    30 -> Option B
  4. Quick Check:

    Top element after pushes = 30 [OK]
Hint: Peek shows last pushed element [OK]
Common Mistakes:
  • Confusing peek with pop output
  • Assuming peek returns bottom element
  • Expecting exception on non-empty stack
4. Identify the error in the following code snippet that tries to peek the top element of a stack:
Stack<String> stack = new Stack<>();
System.out.println(stack.peek());
medium
A. Throws EmptyStackException at runtime
B. Prints empty string
C. Compilation error: peek() not found
D. No error, prints null

Solution

  1. Step 1: Check stack initialization and usage

    The stack is created but no elements are pushed before peek is called.
  2. Step 2: Understand peek behavior on empty stack

    Calling peek() on an empty stack throws EmptyStackException at runtime.
  3. Final Answer:

    Throws EmptyStackException at runtime -> Option A
  4. Quick Check:

    peek() on empty stack throws exception [OK]
Hint: Peek on empty stack throws exception [OK]
Common Mistakes:
  • Assuming peek returns null if empty
  • Expecting compile-time error
  • Thinking it prints empty string
5. Given a stack with elements [5, 10, 15] (5 at bottom, 15 at top), which sequence of operations will peek the top element without removing it and then add 20 on top?
1. stack.peek();
2. stack.push(20);
3. stack.pop();
4. stack.peek();

Select the correct order of operations to achieve this.
hard
A. 3, 1, 2
B. 2, 1
C. 1, 2
D. 1, 3, 2

Solution

  1. Step 1: Peek top element without removing

    Operation 1 (stack.peek()) returns 15 without removing it.
  2. Step 2: Add 20 on top

    Operation 2 (stack.push(20)) adds 20 on top, so stack becomes [5, 10, 15, 20].
  3. Final Answer:

    1, 2 -> Option C
  4. Quick Check:

    Peek then push = 1, 2 [OK]
Hint: Peek first, then push new element [OK]
Common Mistakes:
  • Popping before peek removes top
  • Pushing before peek changes top
  • Incorrect operation order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard