Java Stack Class

Introduction

The Stack class in Java, part of the java.util package, represents a last-in-first-out (LIFO) stack of objects. It extends the Vector class with five operations that allow a vector to be treated as a stack. 

The Stack class provides methods to push and pop elements, as well as to peek at the top element, check if the stack is empty, and search for an element in the stack.

Table of Contents

  1. What is the Stack Class?
  2. Common Methods
  3. Examples of Using the Stack Class
  4. Conclusion

1. What is the Stack Class?

The Stack class represents a stack data structure, which follows the LIFO principle. It is a subclass of Vector and provides methods for typical stack operations. Being a subclass of Vector, Stack inherits all the methods from Vector, making it a versatile but sometimes less efficient choice for stack operations compared to more modern data structures.

2. Common Methods

  • push(E item): Pushes an item onto the top of the stack.
  • pop(): Removes the object at the top of the stack and returns that object as the value of this function.
  • peek(): Looks at the object at the top of the stack without removing it from the stack.
  • empty(): Tests if this stack is empty.
  • search(Object o): Returns the 1-based position where an object is on this stack.

3. Examples of Using the Stack Class

Example 1: Basic Usage of Stack

This example demonstrates basic stack operations such as push, pop, and peek.

import java.util.Stack;

public class BasicStackExample {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();

        // Pushing elements onto the stack
        stack.push("One");
        stack.push("Two");
        stack.push("Three");

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

        // Popping elements from the stack
        System.out.println("Popped element: " + stack.pop());
        System.out.println("Popped element: " + stack.pop());

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

        // Searching for an element
        stack.push("Four");
        stack.push("Five");
        System.out.println("Position of 'Four': " + stack.search("Four"));
    }
}

Output:

Top element: Three
Popped element: Three
Popped element: Two
Is the stack empty? false
Position of 'Four': 2

Example 2: Using Stack for Expression Evaluation

This example demonstrates using a stack to evaluate a simple arithmetic expression.

import java.util.Stack;

public class ExpressionEvaluation {
    public static void main(String[] args) {
        String expression = "3 4 + 2 * 7 /";
        System.out.println("Result of expression evaluation: " + evaluateExpression(expression));
    }

    public static int evaluateExpression(String expression) {
        Stack<Integer> stack = new Stack<>();
        String[] tokens = expression.split(" ");

        for (String token : tokens) {
            if (isOperator(token)) {
                int b = stack.pop();
                int a = stack.pop();
                int result = applyOperator(token, a, b);
                stack.push(result);
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }

    private static boolean isOperator(String token) {
        return "+-*/".contains(token);
    }

    private static int applyOperator(String operator, int a, int b) {
        switch (operator) {
            case "+":
                return a + b;
            case "-":
                return a - b;
            case "*":
                return a * b;
            case "/":
                return a / b;
        }
        throw new IllegalArgumentException("Invalid operator: " + operator);
    }
}

Output:

Result of expression evaluation: 2

Example 3: Using Stack for Balanced Parentheses Check

This example demonstrates using a stack to check if an expression has balanced parentheses.

import java.util.Stack;

public class BalancedParentheses {
    public static void main(String[] args) {
        String expression1 = "(a + b) * (c + d)";
        String expression2 = "(a + b) * (c + d))";

        System.out.println("Expression 1 is balanced: " + isBalanced(expression1));
        System.out.println("Expression 2 is balanced: " + isBalanced(expression2));
    }

    public static boolean isBalanced(String expression) {
        Stack<Character> stack = new Stack<>();

        for (char ch : expression.toCharArray()) {
            if (ch == '(') {
                stack.push(ch);
            } else if (ch == ')') {
                if (stack.isEmpty() || stack.pop() != '(') {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

Output:

Expression 1 is balanced: true
Expression 2 is balanced: false

4. Conclusion

The Stack class in Java provides a straightforward and convenient way to work with stack data structures. Despite being a subclass of Vector, which can lead to some inefficiencies, it is still widely used for its simplicity. The examples provided demonstrate common usage patterns and highlight the capabilities of the Stack class, making it useful for various applications such as expression evaluation and checking balanced parentheses.

Comments