Java Stack

Introduction

A Stack is a collection class that 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 usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.

Table of Contents

  1. What is Stack?
  2. Key Points About Stack
  3. Creating a Stack and Adding Elements
  4. Accessing Elements in a Stack
  5. Removing Elements from a Stack
  6. Iterating Over a Stack
  7. Searching for Elements in a Stack
  8. Example: Comprehensive Usage of Stack
  9. Common Stack Methods
  10. Conclusion

1. What is Stack?

A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The element added last will be the first one to be removed. It is commonly used in scenarios where you need to manage elements in a particular order, such as parsing expressions, managing function calls, and undo mechanisms in software applications.

2. Key Points About Stack

  • LIFO Principle: Last In, First Out.
  • Extends Vector: Inherits properties and methods from the Vector class.
  • Thread-Safe: Stack is synchronized.
  • Supports Common Operations: push, pop, peek, isEmpty, and search.

3. Creating a Stack and Adding Elements

You can create a Stack and add elements using the push method.

Example:

In this example, we create a Stack of strings and add a few elements to it.

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        // Creating a Stack
        Stack<String> stack = new Stack<>();

        // Adding elements to the Stack
        stack.push("Apple");
        stack.push("Banana");
        stack.push("Cherry");

        // Displaying the Stack
        System.out.println("Stack: " + stack);
    }
}

Output:

Stack: [Apple, Banana, Cherry]

4. Accessing Elements in a Stack

You can access elements in a Stack using the peek method to view the top element without removing it.

Example:

In this example, we demonstrate how to access the top element in a Stack.

import java.util.Stack;

public class AccessStack {
    public static void main(String[] args) {
        // Creating a Stack
        Stack<String> stack = new Stack<>();
        stack.push("Apple");
        stack.push("Banana");
        stack.push("Cherry");

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

Output:

Top element: Cherry

5. Removing Elements from a Stack

You can remove elements from a Stack using the pop method, which removes and returns the top element.

Example:

In this example, we demonstrate how to remove elements from a Stack.

import java.util.Stack;

public class RemoveStack {
    public static void main(String[] args) {
        // Creating a Stack
        Stack<String> stack = new Stack<>();
        stack.push("Apple");
        stack.push("Banana");
        stack.push("Cherry");

        // Removing the top element
        System.out.println("Removed element: " + stack.pop());

        // Displaying the Stack after removal
        System.out.println("Stack after removal: " + stack);
    }
}

Output:

Removed element: Cherry
Stack after removal: [Apple, Banana]

6. Iterating Over a Stack

You can iterate over a Stack using various methods such as a simple for-each loop, iterator, and listIterator.

Example:

In this example, we demonstrate different ways to iterate over a Stack.

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;

public class IterateStack {
    public static void main(String[] args) {
        // Creating a Stack
        Stack<String> stack = new Stack<>();
        stack.push("Apple");
        stack.push("Banana");
        stack.push("Cherry");

        // Using simple for-each loop
        System.out.println("Using simple for-each loop:");
        for (String fruit : stack) {
            System.out.println(fruit);
        }

        // Using iterator
        System.out.println("Using iterator:");
        Iterator<String> iterator = stack.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Using listIterator
        System.out.println("Using listIterator:");
        ListIterator<String> listIterator = stack.listIterator();
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }
    }
}

Output:

Using simple for-each loop:
Apple
Banana
Cherry
Using iterator:
Apple
Banana
Cherry
Using listIterator:
Apple
Banana
Cherry

7. Searching for Elements in a Stack

You can search for elements in a Stack using the search method, which returns the 1-based position from the top of the stack.

Example:

In this example, we demonstrate how to search for elements in a Stack.

import java.util.Stack;

public class SearchStack {
    public static void main(String[] args) {
        // Creating a Stack
        Stack<String> stack = new Stack<>();
        stack.push("Apple");
        stack.push("Banana");
        stack.push("Cherry");

        // Searching for elements
        System.out.println("Position of 'Banana': " + stack.search("Banana"));
        System.out.println("Position of 'Apple': " + stack.search("Apple"));
        System.out.println("Position of 'Cherry': " + stack.search("Cherry"));
    }
}

Output:

Position of 'Banana': 2
Position of 'Apple': 3
Position of 'Cherry': 1

8. Example: Comprehensive Usage of Stack

Example:

In this comprehensive example, we demonstrate the common operations on a Stack.

import java.util.Stack;

public class ComprehensiveStackExample {
    public static void main(String[] args) {
        // Creating a Stack
        Stack<Integer> stack = new Stack<>();

        // Adding elements to the Stack
        stack.push(1);
        stack.push(2);
        stack.push(3);

        // Displaying the Stack
        System.out.println("Stack: " + stack);

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

        // Removing the top element
        System.out.println("Removed element: " + stack.pop());

        // Displaying the Stack after removal
        System.out.println("Stack after removal: " + stack);

        // Searching for elements
        System.out.println("Position of '2': " + stack.search(2));
        System.out.println("Position of '1': " + stack.search(1));

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

Output:

Stack: [1, 2, 3]
Top element: 3
Removed element: 3
Stack after removal: [1, 2]
Position of '2': 1
Position of '1': 2
Is the Stack empty? false

9. Common Stack() Methods

Adding Elements

  • push(E item): Pushes an item onto the top of the stack.

Removing Elements

  • pop(): Removes and returns the top item of the stack.

Accessing Elements

  • peek(): Returns the top item of the stack without removing it.

Checking Stack Status

  • isEmpty(): Tests if the stack is empty.

Searching for Elements

  • search(Object o): Returns the 1-based position from the top of the stack.

10. Conclusion

The Stack class in Java is a versatile data structure that provides a LIFO (Last In, First Out) mechanism. It extends the Vector class and supports standard stack operations such as push, pop, and peek. Understanding how to use the Stack class effectively can help you manage collections of objects in scenarios where order and reversibility are important. With methods for adding, removing, accessing, iterating, and searching elements, the Stack class offers a comprehensive solution for stack-based data management in Java applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top