Java Stack Collection

A pictorial representation of the stack is given below.

pictorial representation of the stack

As shown in the above sequence of representation, initially the stack is empty and the top of the stack is set to -1. Then we initiate a “push” operation that is used to add an element to the stack.

So in the second representation, we push element 10. At this point, the top is incremented. We again push element 20 in the stack thereby incrementing the top furthermore.

In the last representation, we initiate a “pop” operation. This operation is used to remove an element from the stack. An element currently pointed to ‘Top’ is removed by the pop operation.

A stack data structure supports the following operations:

  • Push: Adds an element to the stack. As a result, the value of the top is incremented.
  • Pop: An element is removed from the stack. After the pop operation, the value of the top is decremented.
  • Peek: This operation is used to look up or search for an element. The value of the top is not modified.

The top of the stack that is used as an end to add/remove elements from the stack can also have various values at a particular instant. If the size of the stack is N, then the top of the stack will have the following values at different conditions depending on what state the stack is in.

Status of stack Top value
Stack Empty -1
One element in the stack 0
Stack full N-1
Overflow (elements > N) N

Stack Class In Java

Java Collection Framework provides a class named “Stack”. This Stack class extends the Vector class and implements the functionality of the Stack data structure.

The below diagram shows the hierarchy of the Stack class.

Hierarchy of stack class in Java

As shown in the above diagram, the Stack class inherits the Vector class which in turn implements the List Interface of Collection interface.

The Stack class is a part of java.util package. To include Stack class in the program, we can use the import statement as follows.

import java.util.*;

or

import java.util.Stack;

Create A Stack In Java

Once we import the Stack class, we can create a Stack object as shown below:

Stack mystack = new Stack();

We can also create a generic type of Stack class object as follows:

Stack<data_type> myStack = new Stack<data_type>;

Here data_type can be any valid data type in Java.

For example, we can create the following Stack class objects.

Stack<Integer> stack_obj = new Stack<>();
            Stack<String> str_stack = new Stack<>();

Stack API Methods In Java

The Stack class provides methods to add, remove, and search data in the Stack. It also provides a method to check if the stack is empty. We will discuss these methods in the below section.

Stack Push Operation

The push operation is used to push or add elements into the stack. Once we create a stack instance, we can use the push operation to add the elements of the stack object type to the stack.

The following piece of code is used to initialize an integer stack with the values.

Stack<Integer> myStack = new Stack<>();
             myStack.push(10);
             myStack.push(15);
             myStack.push(20);

The initial stack obtained as a result of the above piece of code execution is shown below:

initial stack

If we perform another push() operation as shown below,

push(25);

The resultant stack will be:

The resultant stack

Stack Pop Operation

We can remove the element from the stack using the “pop” operation. The element pointed by the Top at present is popped off the stack.

The following piece of code achieves this.

Stack<Integer> intStack = new Stack<>();
            intStack.push(100);
            intStack.push(200);
            int val = intStack.pop();

The variable val will contain the value 200 as it was the last element pushed into the stack.

The stack representation for push and pop operation is as follows:

push and pop operation

Stack Peek Operation

The peek operation returns the Top of the stack without removing the element. In the above stack example, “intStack.peek ()” will return 200.

Stack isEmpty Operation

The isEmpty () operation of the Stack class checks if the stack object is empty. It returns true if the Stack has no elements in it else returns false.

Stack Search Operation

We can search for an element on the stack using the search () operation. The search () operation returns the index of the element being searched for. This index is counted from the top of the stack.

Stack<Integer> intStack = new Stack<> ();
            intStack.push (100);
            intStack.push (200);
            int index = inStack.search(100);  //index will have the value 2.

Stack Size

The size of the Stack object is given by the java.util.Stack.size () method. It returns the total number of elements in the stack.

The following example prints the stack size.

Stack<Integer> myStack = new Stack<Integer>();
             myStack.push(100);
             myStack.push(200);
             myStack.push(300);
             System.out.println("Stack size:" + myStack.size()); //Stack size: 3

Print / Iterate Stack Elements

We can declare an iterator for the Stack and then traverse through the entire Stack using this iterator. This way we can visit and print each stack element one by one.

The following program shows the way to iterate Stack using an iterator.

import java.util.*;
 
public class Main
{
    public static void main(String[] args) {
        //declare and initialize a stack object
        Stack<String> stack = new Stack<String>();
                stack.push("PUNE");
                stack.push("MUMBAI");
            stack.push("NASHIK");
                System.out.println("Stack elements:");
                //get an iterator for the stack
                Iterator iterator = stack.iterator();
                //traverse the stack using iterator in a loop and print each element
                while(iterator.hasNext()){
                        System.out.print(iterator.next() + " ");
             
                }
    }
}

Output:

Stack elements:
PUNE MUMBAI NASHIK

Stack output

Stack Using Java 8

We can also print or traverse the stack elements using Java 8 features like Stream APIs, forEach, and forEachRemaining constructs.

The following program demonstrates the usage of Java 8 constructs to traverse through the stack.

import java.util.*;
import java.util.stream.*;
 
public class Main  {
    public static void main(String[] args) {
        //declare and initialize a stack object
        Stack<String> stack = new Stack<String>();
                stack.push("PUNE");
                stack.push("MUMBAI");
                stack.push("NASHIK");
     
                System.out.println("Stack elements using Java 8 forEach:");
                //get a stream for the stack
                Stream stream = stack.stream();
                //traverse though each stream object using forEach construct of Java 8
                stream.forEach((element) -> {
                    System.out.print(element + " ");  // print element
                });
                System.out.println("\nStack elements using Java 8 forEachRemaining:");
                //define an iterator for the stack
             Iterator<String> stackIterator = stack.iterator();
                //use forEachRemaining construct to print each stack element
                stackIterator.forEachRemaining(val -> {
                        System.out.print(val + " ");
                });
    }
}

Output:

Stack elements using Java 8 forEach:
PUNE MUMBAI NASHIK
Stack elements using Java 8 forEachRemaining:
PUNE MUMBAI NASHIK

output - Stack using Java 8

Stack Implementation In Java

The following program implements the detailed stack demonstrating the various stack operations.

import java.util.Stack;
 
public class Main {
    public static void main(String a[]){
        //declare a stack object
        Stack<Integer> stack = new Stack<>();
        //print initial stack
        System.out.println("Initial stack : "  + stack);
        //isEmpty ()
        System.out.println("Is stack Empty? : "  + stack.isEmpty());
        //push () operation
        stack.push(10);
        stack.push(20);
        stack.push(30);
        stack.push(40);
        //print non-empty stack
        System.out.println("Stack after push operation: "  + stack);
        //pop () operation
        System.out.println("Element popped out:"  + stack.pop());
        System.out.println("Stack after Pop Operation : "  + stack);
        //search () operation
        System.out.println("Element 10 found at position: "  + stack.search(10));
        System.out.println("Is Stack empty? : "  + stack.isEmpty());
    }
}                                                                       

Output:

Initial stack : []
Is stack Empty? : true
Stack after push operation: [10, 20, 30, 40]
Element popped out:40
Stack after Pop Operation : [10, 20, 30]
Element 10 found at position: 3
Is Stack empty? : false

output - Stack Implementation

Stack To Array In Java

The stack data structure can be converted to an Array using ‘toArray()’ method of the Stack class.

The following program demonstrates this conversion.

import java.util.*;
import java.util.stream.*;
 
public class Main
{
    public static void main(String[] args) {
        //declare and initialize a stack object
        Stack<String> stack = new Stack<String>();
        stack.push("PUNE");
        stack.push("MUMBAI");
        stack.push("NASHIK");
        //print the stack
        System.out.println("The Stack contents: " + stack);
   
        // Create the array and use toArray() method to convert stack to array
        Object[] strArray = stack.toArray();
        //print the array
        System.out.println("The Array contents:");
        for (int j = 0; j < strArray.length; j++)
            System.out.print(strArray[j]+ " ");
    }
}

Output:

The Stack contents: [PUNE, MUMBAI, NASHIK]
The Array contents:
PUNE MUMBAI NASHIK

output - STACK TO ARRAY IN JAVA

Stack Implementation In Java Using Array

The stack can be implemented using an Array. All the stack operations are carried out using an array.

The below program demonstrates the Stack implementation using an array.

import java.util.*;
//Stack class
class Stack { 
    int top;            //define top of stack
    int maxsize = 5;    //max size of the stack 
    int[] stack_arry = new int[maxsize];  //define array that will hold stack elements
    Stack(){            //stack constructor; initially top = -1
        top = -1
    }   
    boolean isEmpty(){          //isEmpty () method
        return (top < 0); 
    
   boolean push (int val){     //push () method 
        if(top == maxsize-1) { 
            System.out.println("Stack Overflow !!"); 
            return false
        
        else 
            top++; 
            stack_arry[top]=val; 
            return true
        
    
    boolean pop () {            //pop () method
        if (top == -1) { 
            System.out.println("Stack Underflow !!"); 
            return false
        
        else  
             
            System.out.println("\nItem popped: " + stack_arry[top--]); 
            return true
        
    
    void display () {           //print the stack elements 
        System.out.println("Printing stack elements ....."); 
        for(int i = top; i>=0;i--) { 
            System.out.print(stack_arry[i] + " "); 
        
    
 
public class Main { 
public static void main(String[] args) { 
    //define a stack object
    Stack stck = new Stack();
    System.out.println("Initial Stack Empty : " + stck.isEmpty());
    //push elements
    stck.push(10);
    stck.push(20);
    stck.push(30);
    stck.push(40);
    System.out.println("After Push Operation...");
    //print the elements
    stck.display();
    //pop two elements from stack
    stck.pop();
    stck.pop();
    System.out.println("After Pop Operation...");
    //print the stack again
    stck.display();
}                                                            

Output:

Initial Stack Empty : true
After Push Operation…
Printing stack elements …..
40 30 20 10
Item popped: 40

Item popped: 30
After Pop Operation…
Printing stack elements …..
20 10

output - Stack implementation in java using array

Stack Implementation Using Linked List

The stack can also be implemented using a linked list just like how we have done using arrays. One advantage of using a linked list for implementing stack is that it can grow or shrink dynamically. We need not have a maximum size restriction like in arrays.

The following program implements a linked list to perform stack operations.

import static java.lang.System.exit;
   
// Stack class using LinkedList
class Stack_Linkedlist {
   
    // Define Node of LinkedList
    private class Node {
        int data; // node data
        Node nlink; // Node link
    }
    // top of the stack
    Node top;
    // stack class Constructor
    Stack_Linkedlist()  {
        this.top = null;
    }
   
    // push () operation
    public void push(int val)  {
        // create a new node
        Node temp = new Node();
   
        // checks if the stack is full
        if (temp == null) {
            System.out.print("\nStack Overflow");
            return;
        }
   
        // assign val to node
        temp.data = val;
   
        // set top of the stack to node link
        temp.nlink = top;
   
        // update top
        top = temp;
    }  
      // isEmpty () operation
    public boolean isEmpty()  {
        return top == null;
    }
 
  // peek () operation
    public int peek()  {
        // check if the stack is empty
        if (!isEmpty()) {
            return top.data;
        }
        else {
            System.out.println("Stack is empty!");
            return -1;
        }
    }
   
    // pop () operation
    public void pop() {
        // check if stack is out of elements
        if (top == null) {
            System.out.print("\nStack Underflow!!");
            return;
        }
        // set top to point to next node
        top = (top).nlink;
    }
   
    //print stack contents
    public void display()   {
        // check for stack underflow
        if (top == null) {
            System.out.printf("\nStack Underflow!!");
            exit(1);
        }
        else {
            Node temp = top;
            System.out.println("Stack elements:");
            while (temp != null) {
                  // print node data
                System.out.print(temp.data + "->");
                // assign temp link to temp
                temp = temp.nlink;
            }
        }
    }
}
 
public class Main {
    public static void main(String[] args)
    {
        // Create a stack class object
        Stack_Linkedlist stack_obj = new Stack_Linkedlist();
        // push values into the stack
        stack_obj.push(9);
        stack_obj.push(7);
        stack_obj.push(5);
        stack_obj.push(3);
        stack_obj.push(1);
   
        // print Stack elements
        stack_obj.display();
   
        // print current stack top
        System.out.println("\nStack top : " + stack_obj.peek());
 
        // Pop elements twice
        System.out.println("Pop two elements");
        stack_obj.pop();
        stack_obj.pop();
   
        // print Stack elements
        stack_obj.display();
   
        // print new stack top
        System.out.println("\nNew Stack top:" + stack_obj.peek());
    }
}

Output:

Stack elements:
1->3->5->7->9->

Stack top : 1
Pop two elements
Stack elements:
5->7->9->

New Stack top:5

output - Stack implementation using a linked list

Frequently Asked Questions

Q #1) What are Stacks in Java?

Answer: A stack is a LIFO (Last in, First out) data structure for storing elements. The stack elements are added or removed from the stack from one end called Top of the stack.

The addition of an element to the stack is done using the Push operation. The deletion of elements is done using pop operation. In Java, a stack is implemented using the Stack class.

Q #2) Is Stack a Collection in Java?

Answer: Yes. The stack is a legacy collection in Java that is available from Collection API in Java 1.0 onwards. Stack inherits the Vector class of the List interface.

Q #3) Is Stack an Interface?

Answer: Interface<E> stack is an interface that describes the last-in, first-out structure and is used for storing the state of recursive problems.

Q #4) What are Stacks used for?

Answer: Following are the main applications of the stack:

  • Expression evaluation and conversions: Stack is used for converting expressions into postfix, infix, and prefix. It is also used to evaluate these expressions.
  • The stack is also used for parsing syntax trees.
  • The stack is used to check parentheses in an expression.
  • The stack is used for solving backtracking problems.
  • Function calls are evaluated using stacks.

Q #5) What are the Advantages of the Stack?

Answer: Variables stored on stack are destroyed automatically when returned. Stacks are a better choice when memory is allocated and deallocated. Stacks also clean up the memory. Apart from that stacks can be used effectively to evaluate expressions and parse the expressions.

Conclusion

This completes our tutorial on Stacks in Java. Stack class is a part of the collection API and supports push, pop, peek, and search operations. The elements are added or removed to/from the stack at one end only. This end is called the top of the stack.

In this tutorial, we have seen all the methods supported by the stack class. We have also implemented the stack using arrays and linked lists.