Java

Stack peek() Method in Java

The Stack peek() method in Java is an essential concept for understanding how stack data structures work. It allows developers to access the top element of a stack without removing it. This guide explains the peek method in a clear, structured, and beginner-friendly manner while also covering practical use cases and advanced considerations.

What Is a Stack in Java?

A Stack is a linear data structure that follows the Last In, First Out (LIFO) principle. The element added most recently is the first one to be removed.

Key Characteristics of Stack

  • Insertion and removal occur only at the top
  • Follows LIFO order
  • Useful for recursive algorithms and history tracking

In Java, the Stack class is part of the java.util package and extends the Vector class.

What Is the peek() Method in Java Stack?

The peek() method in Java Stack returns the element at the top of the stack without removing it. This makes it useful when you want to inspect the current top element while keeping the stack unchanged.

Syntax of Stack peek() Method

E peek()

The method returns the element of type E present at the top of the stack.

How the peek() Method Works

Internally, the peek() method accesses the element at index size() - 1. Since Stack extends Vector, it uses indexed storage to retrieve the top element.

Important Points

  • Does not remove the element
  • Does not change stack size
  • Throws EmptyStackException if stack is empty

Difference Between peek(), pop(), and push()

Method Purpose Stack Modified
push() Adds element to the top Yes
pop() Removes and returns top element Yes
peek() Returns top element only No

Basic Example of Stack peek() Method in Java

import java.util.Stack; public class StackPeekExample { public static void main(String[] args) { Stack stack = new Stack<>(); stack.push(5); stack.push(10); stack.push(15); System.out.println("Top element: " + stack.peek()); System.out.println("Stack after peek: " + stack); } }

Explanation

  • Elements are added using push()
  • peek() returns the top element (15)
  • The stack remains unchanged

Real-World Use Cases of Stack peek()

Undo Operations

Text editors use stacks to track actions. peek() helps check the latest action before undoing.

Expression Evaluation

peek() is used to inspect operators while parsing arithmetic expressions.

Browser Navigation

Browsers manage page history using stacks. peek() shows the current page without altering history.

Handling Empty Stack Safely

Calling peek() on an empty stack causes an EmptyStackException. Always verify the stack state.

if (!stack.isEmpty()) { System.out.println(stack.peek()); }

Using peek() with Custom Objects

class Task { String name; Task(String name) { this.name = name; } } Stack taskStack = new Stack<>(); taskStack.push(new Task("Review Code")); Task currentTask = taskStack.peek();

This shows that peek() works with primitive wrappers and custom objects alike.

Common Mistakes to Avoid

  • Assuming peek() removes elements
  • Calling peek() without checking isEmpty()
  • Using Stack when ArrayDeque may be more suitable

Undo Operations

Undo operations in applications like text editors or design software often rely on stacks to track user actions. Every action performed by the user (typing, deleting, formatting) is pushed onto a stack. When the user clicks "Undo," the application uses the peek() method to inspect the most recent action before deciding whether to remove it or perform additional checks.

// Example of undo operation using Java Stack import java.util.Stack; public class UndoExample { public static void main(String[] args) { Stack actions = new Stack<>(); // User performs actions actions.push("Typed 'Hello'"); actions.push("Deleted 'o'"); actions.push("Typed ' World'"); // Peek the last action System.out.println("Last action: " + actions.peek()); // Outputs: Typed ' World' // Undo the last action String undoneAction = actions.pop(); System.out.println("Undone action: " + undoneAction); System.out.println("Stack after undo: " + actions); } }

Explanation:

  • Actions are pushed onto the stack as they occur.
  • The
    peek() method allows inspecting the last action without removing it.
  • The
    pop() method is used to actually undo the action.
  • This mechanism ensures that actions can be undone in reverse order (LIFO).

Best Practices

  • Use peek() only when inspection is needed
  • Combine peek() with condition checks
  • Choose the right stack implementation

Frequently Asked Questions

What is the main purpose of peek() in Java Stack?

It allows you to view the top element without removing it.

Does peek() change stack size?

No, the stack remains unchanged.

What exception does peek() throw?

EmptyStackException if the stack has no elements.

Is peek() faster than pop()?

Both are constant-time operations, but peek() avoids modification.

Can peek() be used with generics?

Yes, it fully supports generic types.

Conclusion

The Stack peek() method in Java provides a safe and efficient way to access the top element of a stack without modifying it. By understanding its behavior, differences from pop(), and real-world use cases, developers can write cleaner and more reliable Java code.

line

Copyrights © 2024 letsupdateskills All rights reserved