Java Stack Tutorial: Stack Class Implementation With Examples

This Tutorial Explains What is Stack in Java, Java Stack Class, Stack API Methods, Stack Implementation using Array & Linked List with the help of Examples:

A stack is an ordered data structure belonging to the Java Collection Framework. In this collection, the elements are added and removed from one end only. The end at which the elements are added and removed is called “Top of the Stack”.

As addition and deletion are done only at one end, the first element added to the stack happens to be the last element removed from the stack. Thus stack is called a LIFO (Last-in, First-out) data structure.

=> Take A Look At The Java Beginners Guide Here

Stack Collection in Java

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 stackTop value
Stack Empty-1
One element in the stack0
Stack fullN-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.*;


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<>();

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,


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<>();
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 =;  //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>();
 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>();
        		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
            			System.out.print( + " "); 


Stack elements:

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.*;

public class Main  {
	public static void main(String[] args) {
		//declare and initialize a stack object
		Stack<String> stack = new Stack<String>();
        		System.out.println("Stack elements using Java 8 forEach:");
        		//get a stream for the stack
        		Stream 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 + " ");


Stack elements using Java 8 forEach:
Stack elements using Java 8 forEachRemaining:

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
        //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: "  +;
        System.out.println("Is Stack empty? : "  + stack.isEmpty());


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.*;

public class Main
	public static void main(String[] args) {
		//declare and initialize a stack object
		Stack<String> stack = new Stack<String>();
        //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]+ " "); 


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


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  {  
            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
    System.out.println("After Push Operation...");
    //print the elements
    //pop two elements from stack
    System.out.println("After Pop Operation...");
    //print the stack again


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()  { = 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"); 
        // assign val to node = 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()) { 
        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!!"); 
        // 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!!"); 
        else { 
            Node temp = top;
            System.out.println("Stack elements:");
            while (temp != null) { 
                  // print node data
                System.out.print( + "->");
                // 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
        // print Stack elements 
        // print current stack top
        System.out.println("\nStack top : " + stack_obj.peek());

        // Pop elements twice 
        System.out.println("Pop two elements");
        // print Stack elements 
        // print new stack top 
        System.out.println("\nNew Stack top:" + stack_obj.peek()); 


Stack elements:

Stack top : 1
Pop two elements
Stack elements:

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.


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.

We will proceed with other collection classes in our subsequent tutorials.

=> Read Through The Easy Java Training Series