Stack

In Java, the Stack interface represents a Last-In-First-Out (LIFO) data structure. It extends the Vector class with respective methods that allow a vector to be treated as a stack.

  1.  Push:

           void push(E item): Adds an item onto the top of the stack.

      2. Pop:

          E pop(): Removes the object at the top of the stack and returns it.

      3. Peek:

         E peek(): Returns the object at the top of the stack without removing it.

      4. Empty:

         boolean empty(): Checks if the stack is empty.

      5. Search:

          int search(Object o): Searches for the specified object and returns its position relative to the top of the stack

                                            (1-based index). Returns -1 if the object is not found.

 

import java.util.EmptyStackException;
import java.util.Stack;

public class StudentStackExample {
    public static void main(String[] args) {
        // Creating a stack to store student names
        Stack<String> studentStack = new Stack<>();

        // Pushing students onto the stack
        studentStack.push("Paani");
        studentStack.push("Mahesh");
        studentStack.push("Datta");
        studentStack.push("Ganesh");
        studentStack.push("Harsha");

        // Displaying the stack of students
        System.out.println("Stack of students:");
        System.out.println(studentStack);

        // Peeking at the top student
        try {
            String topStudent = studentStack.peek();
            System.out.println("\nTop student (peek): " + topStudent);
        } catch (EmptyStackException e) {
            System.out.println("\nStack is empty. No top student to peek.");
        }

        // Popping a student from the stack
        try {
            String poppedStudent = studentStack.pop();
            System.out.println("\nPopped student: " + poppedStudent);
        } catch (EmptyStackException e) {
            System.out.println("\nStack is empty. Cannot pop a student.");
        }

        // Displaying the updated stack
        System.out.println("\nStack after popping:");
        System.out.println(studentStack);

        // Checking if the stack is empty
        System.out.println("\nIs stack empty? " + studentStack.isEmpty());
    }
}

D:\>javac StudentStackExample.java

D:\>java StudentStackExample
Stack of students:
[Paani, Mahesh, Datta, Ganesh, Harsha]

Top student (peek): Harsha

Popped student: Harsha

Stack after popping:
[Paani, Mahesh, Datta, Ganesh]

Is stack empty? falseCode language: CSS (css)
Scroll to Top