The Wayback Machine - https://web.archive.org/web/20240914152836/https://www.geeksforgeeks.org/stack-class-in-java/
Open In App

Stack Class in Java

Last Updated : 24 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Here’s an example of how you can use the Stack class in Java:

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(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);

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

Output
4
3
2
1

Explanation:

  • In this example, we first import the Stack class from the java.util package.
  • We then create a new Stack object called stack using the default constructor.
  • We push four integers onto the stack using the push() method.
  • We then pop the elements from the stack using the pop() method inside a while loop.
  • The isEmpty() method is used to check if the stack is empty before attempting to pop an element.
  • This code creates a stack of integers and pushes 4 integers onto the stack in the order 1 -> 2 -> 3 -> 4.
  • We then pop elements from the stack one by one using the pop() method, which removes and returns the top element of the stack.
  • Since the stack follows a last-in-first-out (LIFO) order, the elements are popped in the reverse order of insertion, resulting in the output shown above.

Java Collection framework provides a Stack class that models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek. The Stack class extends Vector and provides additional functionality specifically for stack operations, such as push, pop, peek, empty, and search. The Stack class can indeed be referred to as a subclass of Vector, inheriting its methods and properties.

The below diagram shows the hierarchy of the Stack class

Stack Class in Java

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

Declaration:

public class Stack<E> extends Vector<E>

All Implemented Interfaces:

  • Serializable: It is a marker interface that classes must implement if they are to be serialized and deserialized.
  • Cloneable: This is an interface in Java which needs to be implemented by a class to allow its objects to be cloned.
  • Iterable<E>: This interface represents a collection of objects which is iterable — meaning which can be iterated.
  • Collection<E>: A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired.
  • List<E>: The List interface provides a way to store the ordered collection. It is a child interface of Collection.
  • RandomAccess: This is a marker interface used by List implementations to indicate that they support fast (generally constant time) random access.

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: 

Java
// Java code for stack implementation

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

class Test
{   
    // 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 various operations on Stack class

1. Adding Elements: In order to add an element to the stack, we can use the push() method. This push() operation place the element at the top of the stack.

Java
// Java program to add the
// elements in the stack
import java.io.*;
import java.util.*;

class StackDemo {
  
      // Main Method
    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: To retrieve or fetch the first element of the Stack or the element present at the top of the Stack, we can use peek() method. The element retrieved does not get deleted or removed from the Stack. 

Java
// Java program to demonstrate the accessing
// of the elements from the stack
import java.util.*;
import java.io.*;

public class StackDemo {

      // Main Method
    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());

        // Displaying the Stack after the Operation
        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: To pop an element from the stack, we can use the pop() method. The element is popped from the top of the stack and is removed from the same.

Java
// Java program to demonstrate the removing
// of the elements from the stack
import java.util.*;
import java.io.*;

public class StackDemo {
    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);

        // Displaying the Stack
        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);
    }
}

Output
Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]

The Stack class provides several other methods for manipulating the stack, such as peek() to retrieve the top element without removing it, search() to search for an element in the stack and return its position, and size() to return the current size of the stack. The Stack class in Java provides only a default constructor, which creates an empty stack. If you want to create a stack with a specified initial capacity, you would need to extend the Vector class (which Stack itself extends) and set the initial capacity in the constructor of your custom class.

Methods in Stack Class 

Method

Description

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.

Methods inherited from class java.util.Vector

Method

Description

add(Object obj)Appends the specified element to the end of this Vector.
add(int index, Object obj)Inserts the specified element at the specified position in this Vector.
addAll(Collection c)

Appends all of the elements in the specified Collection to the end of this Vector, 

in the order that they are returned by the specified Collection’s Iterator.

addAll(int index, Collection c)Inserts all the elements in the specified Collection into this Vector at the specified position.
addElement(Object o)Adds the specified component to the end of this vector, increasing its size by one.
capacity()Returns the current capacity of this vector.
clear()Removes all the elements from this Vector.
clone()Returns a clone of this vector.
contains(Object o)Returns true if this vector contains the specified element.
containsAll(Collection c)Returns true if this Vector contains all the elements in the specified Collection.
copyInto(Object []array)Copies the components of this vector into the specified array.
elementAt(int index)Returns the component at the specified index.
elements()Returns an enumeration of the components of this vector.
ensureCapacity(int minCapacity)

Increases the capacity of this vector, if necessary, to ensure that it can hold 

at least the number of components specified by the minimum capacity argument.

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

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)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)Inserts the specified object as a component in this vector at the specified index.
isEmpty()Tests if this vector has no components.
iterator()Returns an iterator over the elements in this list in proper sequence.
lastElement()Returns the last component of the vector.
lastIndexOf(Object o)

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)

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()Returns a list iterator over the elements in this list (in proper sequence).
listIterator(int index)

Returns a list iterator over the elements in this list (in proper sequence), 

starting at the specified position in the list.

remove(int index)Removes the element at the specified position in this Vector.
remove(Object o)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)Removes from this Vector all of its elements that are contained in the specified Collection.
removeAllElements()Removes all components from this vector and sets its size to zero.
removeElement(Object o)Removes the first (lowest-indexed) occurrence of the argument from this vector.
removeElementAt(int index)Deletes the component at the specified index.
removeRange(int fromIndex, int toIndex)Removes from this list all the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
retainAll(Collection c)Retains only the elements in this Vector that are contained in the specified Collection.
set(int index, Object o)Replaces the element at the specified position in this Vector with the specified element.
setElementAt(Object o, int index)Sets the component at the specified index of this vector to be the specified object.
setSize(int newSize)Sets the size of this vector.
size()Returns the number of components in this vector.
subList(int fromIndex, int toIndex)Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
toArray()Returns an array containing all of the elements in this Vector in the correct order.
toArray(Object []array)

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()Returns a string representation of this Vector, containing the String representation of each element.
trimToSize()Trims the capacity of this vector to be the vector’s current size.

Prioritize use of Deque over Stack

The Stack class in Java is a legacy class and inherits from Vector in Java. It is a thread-safe class and hence involves overhead when we do not need thread safety. It is recommended to use ArrayDeque for stack implementation as it is more efficient in a single-threaded environment.

Java
// A Java Program to show implementation
// of Stack using ArrayDeque

import java.util.*;

class GFG {
    public static void main (String[] args) {
        Deque<Character> stack = new ArrayDeque<Character>();
        stack.push('A');
        stack.push('B');
        System.out.println(stack.peek());
        System.out.println(stack.pop());
    }
}

Output
B
B


One more reason to use Deque over Stack is Deque has the ability to use streams convert to list with keeping LIFO concept applied while Stack does not.

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

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

        stack.push(1);//1 is the top
        deque.push(1);//1 is the top
        stack.push(2);//2 is the top
        deque.push(2);//2 is the top

        List<Integer> list1 = stack.stream().collect(Collectors.toList());//[1,2]
          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());//[2,1]
          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 


Previous Article
Next Article

Similar Reads

What are the negative aspects of Java Stack class inheriting from Vector?
Java Vector: Vectors are analogous to arrays in a way that both of them are used to store data, but unlike an array, vectors are not homogeneous and don't have a fixed size. They can be referred to as growable arrays that can alter their size accordingly. It is relatively a memory-efficient way of handling lists whose size could change drastically.
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Java Virtual Machine (JVM) Stack Area
For every thread, JVM creates a separate stack at the time of thread creation. The memory for a Java Virtual Machine stack does not need to be contiguous. The Java virtual machine only performs two operations directly on Java stacks: it pushes and pops frames. And stack for a particular thread may be termed as Run – Time Stack. Every method call pe
4 min read
Stack search() Method in Java
The java.util.Stack.search(Object element) method in Java is used to search for an element in the stack and get its distance from the top. This method starts the count of the position from 1 and not from 0. The element that is on the top of the stack is considered to be at position 1. If more than one element is present, the index of the element cl
2 min read
Stack empty() Method in Java
The java.util.Stack.empty() method in Java is used to check whether a stack is empty or not. The method is of boolean type and returns true if the stack is empty else false. Syntax: STACK.empty() Parameters: The method does not take any parameters. Return Value: The method returns boolean true if the stack is empty else it returns false. Below prog
4 min read
Stack pop() Method in Java
The Java.util.Stack.pop() method in Java is used to pop an element from the stack. The element is popped from the top of the stack and is removed from the same.Syntax: STACK.pop() Parameters: The method does not take any parameters.Return Value: This method returns the element present at the top of the stack and then removes it.Exceptions: The meth
2 min read
Stack peek() Method in Java
The java.util.Stack.peek() method in Java is used to retrieve or fetch the first element of the Stack or the element present at the top of the Stack. The element retrieved does not get deleted or removed from the Stack. Syntax: STACK.peek() Parameters: The method does not take any parameters. Return Value: The method returns the element at the top
2 min read
Stack push() Method in Java
Java.util.Stack.push(E element) method is used to push an element into the Stack. The element gets pushed onto the top of the Stack. Syntax: STACK.push(E element)Parameters: The method accepts one parameter element of type Stack and refers to the element to be pushed into the stack. Return Value: The method returns the argument passed. It also acce
2 min read
Stack capacity() method in Java with Example
The capacity() method of Stack Class is used to get the capacity of this Stack. That is the number of elements present in this stack container. Syntax: public int capacity() Parameters: This function accepts a parameter E obj which is the object to be added at the end of the Stack. Return Value: The method returns integer value which is the capacit
2 min read
Stack contains() method in Java with Example
The java.util.Stack.contains() method is used to check whether a specific element is present in the Stack or not. So basically it is used to check if a Stack contains any particular element or not. Syntax: Stack.contains(Object element) Parameters: This method takes a mandatory parameter element which is of the type of Stack. This is the element th
2 min read
Stack equals() method in Java with Example
The Java.util.Stack.equals(Object obj) method of Stack class in Java is used verify the equality of an Object with a Stack and compare them. The list returns true only if both Stack contains same elements with same order. Syntax: first_Stack.equals(second_Stack) Parameters: This method accepts a mandatory parameter second_Stack which refers to the
2 min read
Stack get() method in Java with Example
The Java.util.Stack.get() method is used to fetch or retrieve an element at a specific index from a Stack. Syntax: Stack.get(int index) Parameters: This method accepts a mandatory parameter index which is of integer data type. It specifies the position or index of the element to be fetched from the Stack. Return Value: The method returns the elemen
2 min read
Stack indexOf() method in Java with Example
The Java.util.Stack.indexOf(Object element) method is used to check and find the occurrence of a particular element in the Stack. If the element is present then the index of the first occurrence of the element is returned otherwise -1 is returned if the Stack does not contain the element. Syntax: Stack.indexOf(Object element) Parameters: This metho
2 min read
Stack containsAll() method in Java with Example
The containsAll() method of Java Stack is used to check whether two stacks contain the same elements or not. It takes one stack as a parameter and returns True if all of the elements of this stack is present in the other stack. Syntax: public boolean containsAll(Collection C) Parameters: The parameter C is a Collection. This parameter refers to the
2 min read
Stack clear() method in Java with Example
The Java.util.Stack.clear() method is used to remove all the elements from a Stack. Using the clear() method only clears all the element from the Stack and does not delete the Stack. In other words, we can say that the clear() method is used to only empty an existing Stack. Syntax: Stack.clear() Parameters: The method does not take any parameter Re
2 min read
Stack copyInto() method in Java with Example
The java.util.Stack.copyInto() method is used to copy all of the components from this Stack to another Stack, having enough space to hold all of the components of the Stack. It is to be noted that the index of the elements remains unchanged. The elements present in the Stack are replaced by the elements of the Stack. Syntax: Stack.copyInto(Object S
2 min read
Stack insertElementAt() method in Java with Example
The Java.util.Stack.insertElementAt(element, index) method is used to insert a particular element at the specified index of the Stack. Both the element and the position is passed as the parameters. If an element is inserted at a specified index, then all the elements are pushed upward by one and hence the capacity is increased, creating a space for
2 min read
Stack isEmpty() method in Java with Example
The Java.util.Stack.isEmpty() method in Java is used to check and verify if a Stack is empty or not. It returns True if the Stack is empty else it returns False. Syntax: Stack.isEmpty() Parameters: This method does not take any parameter. Return Value: This function returns True if the Stackis empty else it returns False. Below programs illustrate
2 min read
Stack elementAt() method in Java with Example
The Java.util.Stack.elementAt(int pos) method is used to fetch or retrieve an element at a specific index from a Stack. Syntax: Stack.elementAt(int pos) Parameters: This method accepts a mandatory parameter pos of integer data type that specifies the position or index of the element to be fetched from the Stack. Return Value: The method returns the
2 min read
Stack ensureCapacity() method in Java with Example
The ensureCapacity() method of Java.util.Stack class increases the capacity of this Stack instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. Syntax: public void ensureCapacity(int minCapacity) Parameters: This method takes the desired minimum capacity as a parameter. Below
2 min read
Stack firstElement() method in Java with Example
The Java.util.Stack.firstElement() method in Java is used to retrieve or fetch the first element of the Stack. It returns the element present at the 0th index of the Stack Syntax: Stack.firstElement() Parameters: The method does not take any parameter. Return Value: The method returns the first element present in the Stack. Below programs illustrat
2 min read
Stack hashCode() method in Java with Example
The Java.util.Stack.hashCode() method in Java is used to get the hashcode value of this Stack. Syntax: Stack.hashCode() Parameters: The method does not take any parameter. Return Value: The method returns hash code value of this Stack which is of Integer type. Below programs illustrate the Java.util.Stack.hashCode() method: Program 1: Stack with st
2 min read
Stack indexOf(Object, int) method in Java with Example
The Java.util.Stack.indexOf(Object element, int index) method is used to the index of the first occurrence of the specified element in this Stack, searching forwards from index, or returns -1 if the element is not found. More formally, returns the lowest index i such that (i &gt;= index &amp;&amp; Objects.equals(o, get(i))), or -1 if there is no su
2 min read
Stack iterator() method in Java with Example
The Java.util.Stack.iterator() method is used to return an iterator of the same elements as that of the Stack. The elements are returned in random order from what was present in the stack. Syntax: Iterator iterate_value = Stack.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the elements of t
2 min read
Stack elements() method in Java with Example
The Java.util.Stack.elements() method of Stack class in Java is used to get the enumeration of the values present in the Stack. Syntax: Enumeration enu = Stack.elements() Parameters: The method does not take any parameters. Return value: The method returns an enumeration of the values of the Stack. Below programs are used to illustrate the working
2 min read
Stack addElement(E) method in Java with Example
The addElement(E) method of Stack Class is used to append the element passed as a parameter to this function at the end of the Stack. Syntax: boolean addElement(E obj) Here, E is the type of elements maintained by this container. Parameters: This function accepts a parameter E obj which is the object to be added at the end of the Stack. Return Valu
2 min read
Stack addAll(int, Collection) method in Java with Example
The addAll(int, Collection) method of Stack Class is used to append all of the elements from the collection passed as a parameter to this function at a specific index or position of a Stack. Syntax: boolean addAll(int index, Collection C) Parameters: This function accepts two parameters as shown in the above syntax and are described below. index: T
2 min read
Stack addAll(Collection) method in Java with Example
The addAll(Collection) method of Stack Class is used to append all of the elements from the collection passed as a parameter to this function to the end of a Stack keeping in mind the order of return by the collection's iterator. Syntax: boolean addAll(Collection C) Parameters: The method accepts a mandatory parameter C which is a collection of Arr
2 min read
Stack add(Object) method in Java with Example
The add(Object) method of Stack Class appends the specified element to the end of this Stack. Syntax: boolean add(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the Stack. Return Value: This method returns True after successful
2 min read