What Is Stack in Data Structure Java?

//

Larry Thompson

In data structures, a stack is an abstract data type that follows the Last-In-First-Out (LIFO) principle. It can be implemented using arrays or linked lists. In Java, the Stack class is provided by the java.util package and extends the Vector class.

Stack Operations

The Stack class in Java provides various methods to perform operations on a stack:

  • push(element): Adds an element to the top of the stack.
  • pop(): Removes and returns the element at the top of the stack.
  • peek(): Returns the element at the top of the stack without removing it.
  • isEmpty(): Checks if the stack is empty or not.
  • search(element): Searches for an element in the stack and returns its position. The position is counted from the top of the stack, with 1 being the topmost element.

Example: Using Stack in Java

Let’s see an example to understand how to use a stack in Java:


import java.util.Stack;

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

        // Push elements onto the stack
        stack.push(10);
        stack.push(20);
        stack.push(30);

        // Print elements of the stack
        System.out.println("Stack: " + stack);

        // Pop an element from the top of the stack
        int poppedElement = stack.pop();
        System.println("Popped Element: " + poppedElement);

        // Peek the element at the top of the stack
        int peekedElement = stack.peek();
        System.println("Peeked Element: " + peekedElement);

        // Check if the stack is empty
        System.println("Is Stack Empty? " + stack.isEmpty());

        // Search for an element in the stack
        int position = stack.search(20);
        System.println("Position of 20: " + position);
    }
}

The output of the above code will be:


Stack: [10, 20, 30]
Popped Element: 30
Peeked Element: 20
Is Stack Empty? false
Position of 20: 2

Conclusion

In conclusion, a stack is a fundamental data structure that follows the Last-In-First-Out principle. It is widely used in various applications and can be easily implemented using Java’s Stack class. By understanding the operations provided by the Stack class, you can efficiently manipulate elements in a stack and utilize it to solve real-world problems.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy