DEV Community

Uma Maheshwar Amanchi
Uma Maheshwar Amanchi

Posted on

Understanding the Stack Data Structure: A Java Implementation

The stack data structure is fundamental, yet powerful. It operates on the principle of “Last In, First Out” (LIFO), meaning the last element added to the stack will be the first one to be removed. This makes it exceptionally useful in various applications, from parsing expressions in compilers to managing function calls in programming.

In this blog post, we’ll explore the stack data structure through a hands-on Java example, unveiling its operations, uses, and underlying mechanics.

What is a Stack?

Imagine a stack of plates; you can only take the top plate off the stack and can only add a new plate to the top. This is the essence of the stack data structure. It’s a collection that supports two primary operations:

  1. Push: Adds an item to the top of the stack.

  2. Pop: Removes the item from the top of the stack.

Additionally, stacks provide auxiliary operations such as

  • Peek : To view the top item without removing it.

  • isEmpty: To check whether the stack is empty.

  • search(item): Returns the position of existing item in Stack, returns -1 for non existing items.

Java Implementation of Stack

In Java, Stack is a legacy Collection class that extends Vector. Let's dive into a simple program to understand its usage:

import java.util.*;

public class Main {

    public static void main(String[] args) {
        // Initializing a stack to hold String types
        Stack<String> stack = new Stack<String>();

        // Checking if the stack is empty
        System.out.println("Is stack empty? " + stack.empty());

        // Pushing elements into the stack
        stack.push("Hello");
        stack.push("Cricket");
        stack.push("Volleyball");
        stack.push("Hockey");

        // Printing the entire stack
        System.out.println("Stack elements: " + stack);

        // Peeking the top element
        System.out.println("Top element: " + stack.peek());

        // Searching for elements
        System.out.println("Position of 'Cricket': " + stack.search("Cricket"));
        System.out.println("Position of 'Basketball' (not in stack): " + stack.search("Basketball"));

        // Popping elements from the stack
        while (!stack.empty()) {
            System.out.println("Popping: " + stack.pop());
        }

        // Trying to pop from an empty stack will throw EmptyStackException
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Output

Practical Uses of Stack

  • String Reversal: By pushing each character of a string into a stack and popping them, you can reverse the string.

  • Undo/Redo Features: Text editors use stacks to implement undo (by storing previous states) and redo operations.

  • Backtracking Algorithms: From maze solving to parsing expressions, stacks are pivotal in storing previous states for backtracking.

Conclusion

Stacks are a versatile and essential data structure in computer science. Through our Java program, we’ve seen how to implement and work with stacks, understanding their operations and appreciating their potential in solving real-world problems. Whether you’re reversing strings or navigating complex algorithms, the stack is a tool you’ll want in your arsenal.

Remember, understanding these fundamental data structures is key to becoming a proficient programmer and problem solver. Happy coding!

Top comments (0)