Java Stack Class

In this article, we will learn about the Java stack class, Basic operations like adding elements, etc, and its methods with the help of examples.

Introduction

The Stack class in the Java Collection framework represents and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. Aside from the standard push and pop operations, the class also has three additional functions: empty, search, and peek. The class also extends Vector and handles the class as a stack with the five methods indicated. The class can alternatively be referred to as a Vector subclass.

Java Stack Hierarchy
Java Stack Hierarchy

The class supports one default constructor Stack() which is used to create an empty stack.

Declaration:

public class Stack<E> extends Vector<E>

Java Stack Implementation

Elements in a stack are stored and retrieved in the Last In First Out order. That is, pieces are added to the stack’s top and removed from the stack’s top.

Flow of execution
Flow

Creating a Java Stack

To create a stack, we must first import the java.util.Stack package. Here’s how to create a stack in Java when we import the package.

Stack<Type> stacks = new Stack<>();

Here, Type indicates the stack’s type

Example:

// Create Integer type stack
Stack<Integer> stacks = new Stack<>();

// Create String type stack
Stack<String> stacks = new Stack<>();

Java Stack Class Methods

MethodDescription
empty()It returns true if nothing is on the top of the stack. Else, returns false.
peek()Returns the element on the top of the stack, but does not remove it.
pop()Removes and returns the top element of the stack. An ‘EmptyStackException’, An exception is thrown if we call pop() when the invoking stack is empty.
push(Object element)Pushes an element on the top of the stack.
search(Object element)It determines whether an object exists in the stack. If the element is found, It returns the position of the element from the top of the stack. Else, it returns -1.

push() Method

To add an element to the top of the stack, we use the push() method.

Code 01:

import java.util.Stack;

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

        // Add elements to Stack
        fruits.push("Apple");
        fruits.push("Banana");
        fruits.push("Mango");

        System.out.println("Stack: " + fruits);
    }
}

Output:

Stack: [Apple, Banana, Mango]

pop() Method

To remove an element from the top of the stack, we use the pop() method.

Code 02:

import java.util.Stack;

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

        // Add elements to Stack
        fruits.push("Apple");
        fruits.push("Banana");
        fruits.push("Mango");
        System.out.println("Initial Stack: " + fruits);

        // Remove element stacks
        String fruit = fruits.pop();
        System.out.println("Removed Element: " + fruit);
    }
}

Output:

Initial Stack: [Apple, Banana, Mango]
Removed Element: Mango

peek() Method

The peek() method returns an object from the top of the stack.

Code 03:

import java.util.Stack;

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

        // Add elements to Stack
        fruits.push("Apple");
        fruits.push("Banana");
        fruits.push("Mango");
         System.out.println("Stack: " + fruits);

        // Access element from the top
        String fruit = fruits.peek();
        System.out.println("Element at top: " + fruit);
    }
}

Output:

Stack: [Apple, Banana, Mango]
Element at top: Mango

search() Method

To search an element in the stack, we use the search() method. It returns the position of the element from the top of the stack.

Code 04:

import java.util.Stack;

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

        // Add elements to Stack
        fruits.push("Apple");
        fruits.push("Banana");
        fruits.push("Mango");
        System.out.println("Stack: " + fruits);

       // Search an element
        int position = fruits.search("Banana");
        System.out.println("Position of Banana: " + position);
    }
}

Output:

Stack: [Apple, Banana, Mango]
Position of Banana: 2

empty() Method

To check whether a stack is empty or not, we use the empty() method.

Code 05:

import java.util.Stack;

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

        // Add elements to Stack
        fruits.push("Apple");
        fruits.push("Banana");
        fruits.push("Mango");
        System.out.println("Stack: " + fruits);

        // Check if stack is empty
        boolean check = fruits.empty();
        System.out.println(check);
    }
}

Output:

Stack: [Apple, Banana, Mango]
false

Use ArrayDeque Instead of Java Stack

Please keep in mind that the Stack class in Java is a legacy class that derives from Vector. Because it is a thread-safe class, it incurs costs when we do not require thread-safety. ArrayDeque is suggested for stack implementation since it is more efficient in a single-threaded environment.

Code 06:

import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) {
        ArrayDeque<String> fruits= new ArrayDeque<>();

        // Using add()
        fruits.add("Apple");

        // Using addFirst()
        fruits.addFirst("Banana");

        // Using addLast()
        fruits.addLast("Mango");
        System.out.println("ArrayDeque: " + fruits);
    }
}

Output:

ArrayDeque: [Banana, Apple, Mango]

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. Java Constructor

Leave a Comment