Open In App

Stack Class in Java

Last Updated : 06 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, a Stack is a linear data structure that follows the Last In First Out (LIFO) principle and is defined in the java.util package. Internally, it extends the Vector class.

Key Characteristics of Vector

  • Maintains insertion order
  • Allows duplicate and null values
  • Grows dynamically when capacity is exceeded
  • Implements List, RandomAccess, Cloneable and Serializable interfaces
  • Inherits from the AbstractList class

Example: Here, we are implementing the Stack class.

Java
import java.util.Stack;

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

        // Push elements onto the stack
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);

        // Pop elements from the stack
        while(!s.isEmpty()) {
            System.out.println(s.pop());
        }
    }
}

Output
4
3
2
1

Explanation:

  • Elements are added to the stack using the push() method, placing each item on top.
  • A loop runs while the stack is not empty, checked using the empty() method.
  • Elements are removed and printed using the pop() method in LIFO order.

Hierarchy of Stack class

The below diagram shows the hierarchy of the Stack class: 

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

How to Create a Stack?

In order to create a stack, we must import java.util.stack package and use the Stack() constructor of this class. The below example creates an empty Stack.

Stack<E> stack = new Stack<E>();

Here, E is the type of Object.

Example: Here, we are performing various operations in stack.

Java
import java.util.Stack;

class Geeks
{   
    // Pushing element on the top of the stack
    static void stack_push(Stack<Integer> stack)
    {
        for(int i = 0; i < 5; i++)
        {
            stack.push(i);
        }
    }
    // Popping element from the top of the stack
    static void stack_pop(Stack<Integer> stack)
    {
        System.out.println("Pop Operation:");

        for(int i = 0; i < 5; i++)
        {
            Integer y = (Integer) stack.pop();
            System.out.println(y);
        }
    }
    // Displaying element on the top of the stack
    static void stack_peek(Stack<Integer> stack)
    {
        Integer element = (Integer) stack.peek();
        System.out.println("Element on stack top: " + element);
    }
    
    // Searching element in the stack
    static void stack_search(Stack<Integer> stack, int element)
    {
        Integer pos = (Integer) stack.search(element);

        if(pos == -1)
            System.out.println("Element not found");
        else
            System.out.println("Element is found at position: " + pos);
    }
    public static void main (String[] args)
    {
        Stack<Integer> stack = new Stack<Integer>();

        stack_push(stack);
        stack_pop(stack);
        stack_push(stack);
        stack_peek(stack);
        stack_search(stack, 2);
        stack_search(stack, 6);
    }
}

Output
Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found

Performing Different Operations on Stack Class

1. Adding Elements: With the help of push() method we can add element to the stack. The push() method place the element at the top of the stack.

Example: Here we are creating a stack with both default and generic types and pushing element onto the stack.

Java
import java.io.*;
import java.util.*;

class Geeks {
  
    public static void main(String[] args)
    {
        // Default initialization of Stack
        Stack stack1 = new Stack();

        // Initialization of Stack using Generics
        Stack<String> stack2 = new Stack<String>();

        // pushing the elements
        stack1.push("4");
        stack1.push("All");
        stack1.push("Geeks");

        stack2.push("Geeks");
        stack2.push("For");
        stack2.push("Geeks");

        // Printing the Stack Elements
        System.out.println(stack1);
        System.out.println(stack2);
    }
}

Output
[4, All, Geeks]
[Geeks, For, Geeks]

2. Accessing the Element: With the help of peek() method we can fetch the top element of the stack. 

Example: Here, we are using peek() to access the top element of the stack.

Java
import java.util.*;
import java.io.*;

public class Geeks {

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

        // Use push() to add elements into the Stack
        stack.push("Welcome");
        stack.push("To");
        stack.push("Geeks");
        stack.push("For");
        stack.push("Geeks");

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

        // Fetching the element at the head of the Stack
        System.out.println("The element at the top of the"
                           + " stack is: " + stack.peek());

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

Output
Initial Stack: [Welcome, To, Geeks, For, Geeks]
The element at the top of the stack is: Geeks
Final Stack: [Welcome, To, Geeks, For, Geeks]

3. Removing Elements: With the help of pop() method we can delete and return the top element from the stack.

Example: Here, we are removing element from the stack using pop().

Java
import java.util.*;
import java.io.*;

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

        // Use add() method to add elements
        stack.push(10);
        stack.push(15);
        stack.push(30);
        stack.push(20);
        stack.push(5);

        System.out.println("Initial Stack: " + stack);

        // Removing elements using pop() method
        System.out.println("Popped element: " + stack.pop());
        System.out.println("Popped element: "
                           + stack.pop());

        // Displaying the Stack after pop operation
        System.out.println("Stack after pop operation " + stack);
      
       System.out.println("Is stack empty? " + stack.empty()); 
       // Pop remaining elements
        stack.pop();
        stack.pop();
        stack.pop();

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

Output
Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]
Is stack empty? false
Is stack empty? true

Prioritize Use of Deque over Stack

The Stack class in Java is inherits from Vector in Java. It is a thread-safe class. It is recommended to use ArrayDeque for stack implementation as it is more efficient in a single-threaded environment.

Example: Here, we are implementing stack with the help of ArrayDeque.

Java
import java.util.*;
import java.util.stream.Collectors;

class Geeks {
    public static void main (String[] args) {
 
          Stack<Integer> stack = new Stack<>();
        Deque<Integer> deque = new ArrayDeque<>();

        stack.push(1);
        deque.push(1);
        stack.push(2);
        deque.push(2);

        List<Integer> list1 = stack.stream().collect(Collectors.toList());
          System.out.println("Using Stack: ");
          for(int i = 0; i < list1.size(); i++){
              System.out.print(list1.get(i) + " " );
        }
          System.out.println();

        List<Integer> list2 = deque.stream().collect(Collectors.toList());
          System.out.println("Using Deque: ");
          for(int i = 0; i < list2.size(); i++){
              System.out.print(list2.get(i) + " " );
        }
          System.out.println();
      
    }
}

Output
Using Stack: 
1 2 
Using Deque: 
2 1 

Methods in Stack Class 

Method

Description

empty()

This method returns true if nothing is on the top of the stack. Else, returns false.

peek()

This method returns the element on the top of the stack, but does not remove it.

pop()

This method removes and returns the top element of the stack.

push(Object element)

This method pushes an element on the top of the stack.

search(Object element)

This method is used to determine 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.

Methods Inherited from the Vector Class

Method

Description

add(Object obj)This method is used to appends the specified element to the end of the Vector.
add(int index, Object obj)This method is used to inserts the specified element at the specified position in the Vector.
addAll(Collection c)

This method is used to appends all of the elements in the specified Collection to the end of theVector, in the order that they are returned by the specified Collection's Iterator.

addAll(int index, Collection c)This method is used to inserts all the elements in the specified Collection into this Vector at the specified position.
addElement(Object o)This method is used to adds the specified component to the end of the vector
capacity()This method returns the current capacity of the vector.
clear()This method removes all the elements from the Vector.
clone()This method returns a clone of the vector.
contains(Object o)This method returns true if this vector contains the specified element.
containsAll(Collection c)This method returns true if this Vector contains all the elements in the specified Collection.
copyInto(Object []array)This method is used to copies the components of this vector into the specified array.
elementAt(int index)This method returns the component at the specified index.
elements()This method returns an enumeration of the components of the vector.
ensureCapacity(int minCapacity)

This method increases the capacity of the vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.

equals()This method compares the specified Object with the Vector for equality.
firstElement()This method returns the first component (the item at index 0) of the vector.
get(int index)This method returns the element at the specified position in the Vector.
hashCode()This method returns the hash code value for the Vector.
indexOf(Object o)

This method returns the index of the first occurrence of the specified element in this vector or -1 if this vector does not contain the element.

indexOf(Object o, int index)This method returns the index of the first occurrence of the specified element in this vector, searching forwards from the index or returns -1 if the element is not found.
insertElementAt(Object o, int index)This method inserts the specified object as a component in this vector at the specified index.
isEmpty()This method tests if this vector has no components.
iterator()This method returns an iterator over the elements in this list in proper sequence.
lastElement()This method returns the last component of the vector.
lastIndexOf(Object o)

This method returns the index of the last occurrence of the specified element in this vector or -1 If this vector does not contain the element.

lastIndexOf(Object o, int index)

This method returns the index of the last occurrence of the specified element in this vector, searching backward from the index or returns -1 if the element is not found.

listIterator()This method returns a list iterator over the elements in this list (in proper sequence).
listIterator(int index)

This method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.

remove(int index)This method removes the element at the specified position in this Vector.
remove(Object o)This method removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.
removeAll(Collection c)This method removes from this Vector all of its elements that are contained in the specified Collection.
removeAllElements()This method removes all components from this vector and sets its size to zero.
removeElement(Object o)This method removes the first (lowest-indexed) occurrence of the argument from this vector.
removeElementAt(int index)This method deletes the component at the specified index.
removeRange(int fromIndex, int toIndex)This method removes from this list all the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
retainAll(Collection c)This method retains only the elements in this Vector that are contained in the specified Collection.
set(int index, Object o)This method replaces the element at the specified position in this Vector with the specified element.
setElementAt(Object o, int index)This method sets the component at the specified index of this vector to be the specified object.
setSize(int newSize)This method sets the size of this vector.
size()This method returns the number of components in this vector.
subList(int fromIndex, int toIndex)This method returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
toArray()This method returns an array containing all of the elements in this Vector in the correct order.
toArray(Object []array)

This method returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.

toString()This method returns a string representation of this Vector, containing the String representation of each element.
trimToSize()This method trims the capacity of this vector to be the vector's current size.

Stack in Java Collections
Visit Course explore course icon

Similar Reads