Stack Class in Java

Introduction

Stack is a subclass of Vector that implements a standard last-in, first-out stack in Java. In this article, we will learn about the Java Stack class, its methods, and constructors that are provided in the Java programming language.

What is a Stack class in Java?

The Stack represents a last-in, first-out (LIFO) data structure and linear data structure. A stack has two fundamental operations called push and pop. It extends the Vector class with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.

When a stack is first created, it contains no items.

java.lang.Object
    java.util.Vector
        java.util.Stack

As Vector implements List, Stack class is also a List implementation class but does NOT support all operations of Vector or List. As Stack supports LIFO, it is also known as LIFO Lists.

java-stack-class

What is the LIFO mechanism?

The Stack data structure follows the LIFO structure (Last In, First Out). LIFO is a method of processing data in which the last items entered are the first to be removed. This is the opposite of LIFO is FIFO (First In, First Out), in which items are removed in the order they have been entered.

To better understand LIFO, imagine stacking a deck of cards by placing one card on top of the other, starting from the bottom. Once the deck has been fully stacked, you begin to remove the cards, starting from the top. This process is an example of the LIFO method because the last cards to be placed on the deck are the first ones to be removed.

Constructor of Stack Class in Java

Stack only defines the default constructor, which creates an empty stack. The stack includes all the methods defined by Vector and adds several of its own.

Stack()

The Stack class supports one default constructor, Stack(), which is used to create an empty stack. The complete program of the Stack() constructor is listed below.

public class StackConstructorExample {  
    StackConstructorExample() {  
        System.out.println("Empty stack is created");  
    }  
    public static void main(String args[]) {  
        StackConstructorExample stack = new StackConstructorExample();  
    }  
}

The above program generates the following output.

stack-constructor-example-output

Methods of Stack Class in Java


1) Stack push() method in Java

The 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. The method accepts one parameter element of type Stack and refers to the element to be pushed into the stack. The method returns the argument passed.

The program adds the string value to the Stack. The complete program of the Stack.push() method is listed below.

import java.util.*;  
public class PushMethodExample {  
    public static void main(String args[]) {  
        // Creating an empty Stack  
        Stack<String> stack = new Stack<String>();  
        stack.push("Welcome");  
        stack.push("To");  
        stack.push("C#Corner");  
        System.out.println("Initial Stack: " + stack);  
        // Push elements into the stack  
        stack.push("Hello");  
        stack.push("Programmers");  
        // Displaying the final Stack  
        System.out.println("Final Stack: " + stack);  
    }  
} 

The above program generates the following output.

push-method-example-output

The program adds the integer value to the Stack. The complete program of Stack.push() method is listed below.

import java.util.*;  
public class PushElementExample2 {  
    public static void main(String args[]) {  
        // Creating an empty Stack  
        Stack<Integer> stack = new Stack<Integer>();  
        // Use push() to add elements into the Stack  
        stack.push(10);  
        stack.push(15);  
        stack.push(30);  
        stack.push(20);  
        stack.push(5);  
        System.out.println("Initial Stack: " + stack);  
        // Pushing elements into the Stack  
        stack.push(1254);  
        stack.push(4521);  
        System.out.println("Final Stack: " + stack);  
    }  
} 

The above program generates the following output.

push-method-example-output

2) 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. The method does not take any parameters. This method returns the element present at the top of the stack and then removes it. The method throws EmptyStackException is thrown if the stack is empty.

The program adds the string value to the Stack. The complete program of the Stack.push() method is listed below.

import java.util.*;  
public class PopMethodExample {  
    public static void main(String args[]) {  
        // Creating an empty Stack  
        Stack<String> stack = new Stack<String>();  
        stack.push("Welcome");  
        stack.push("To");  
        stack.push("C#Corner");  
        System.out.println("Initial Stack: " + stack);  
        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 peration " + stack);  
    }  
} 

The above program generates the following output.

pop-example-method-example

The program adds the integer value to the Stack. The complete program of Stack.push() method is listed below.

import java.util.*;  
public class PopMethodExample2 {  
    public static void main(String args[]) {  
        // Creating an empty Stack  
        Stack<Integer> STACK = new Stack<Integer>();  
        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);  
    }  
}

The above program generates the following output.

pop-example-method-example

3) 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. The method does not take any argument. The method returns the element at the top of the Stack else. It returns NULL if the Stack is empty. Exception: The method throws EmptyStackException if the stack is empty.

The program adds the string value to the Stack. The complete program of the Stack.push() method is listed below.

import java.util.Stack;  
public class PeekMethodExample {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>();  
        stack.push("Welcome");  
        stack.push("To");  
        stack.push("C#corner");  
        System.out.println("Initial Stack: " + stack);  
        System.out.println("The element at the top of the" + " stack is: " + stack.peek());  
        System.out.println("Final Stack: " + stack);  
    }  
} 

The above program generates the following output.

peek-example-output

The program adds the integer value to the Stack. The complete program of the Stack.push() method is listed below.

import java.util.*;  
public class PeekMethodExample2 {  
    public static void main(String args[]) {  
        Stack<Integer> stack = new Stack<Integer>();  
        stack.push(10);  
        stack.push(15);  
        stack.push(30);  
        stack.push(20);  
        stack.push(5);  
        System.out.println("Initial Stack: " + stack);  
        System.out.println("The element at the top of the" + " stack is: " + stack.peek());  
        System.out.println("Final Stack: " + stack);  
    }  
} 

The above program generates the following output.

4) 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. The method does not take any argument. The method returns a boolean true if the stack is empty else it returns false.

The complete program of Stack.empty() method example for checking whether the Stack is empty or not.

import java.util.*;  
public class EmptyMethodExample {  
    public static void main(String[] args) {  
        Stack<String> STACK = new Stack<String>();  
        System.out.println("Is the stack empty? " + STACK.empty());  
    }  
}

The above program generates the following output.

empty-example-output

Another program of Stack.empty() method example for checking if the Stack is empty or not.

import java.util.*;  
public class EmptyMethodExample2 {  
    public static void main(String[] args) {  
        // Creating an empty Stack   
        Stack<Integer> stack = new Stack<Integer>();  
        // Stacking int values   
        stack.push(8);  
        stack.push(5);  
        stack.push(9);  
        stack.push(2);  
        stack.push(4);  
        System.out.println("The stack is: " + stack);  
        System.out.println("Is the stack empty? " + stack.empty());  
    }  
} 

The above program generates the following output.

empty-example-output2

5) 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 closest to the top is returned. The method returns its position if the element is successfully found and returns -1 if the element is absent.

The method accepts one parameter element, which refers to the element that is required to be searched for in the Stack. The method returns the position of the element if it is successfully found in the stack (taking the count as base 1). Else -1 is returned.

The complete program of Stack.search() method is listed below.

import java.util.*;  
public class SearchMethodExample {  
    public static void main(String[] args) {  
        Stack<String> STACK = new Stack<String>();  
        STACK.push("Hello");  
        STACK.push("4");  
        STACK.push("C#corner");  
        STACK.push("Welcomes");  
        STACK.push("You");  
        System.out.println("The stack is: " + STACK);  
        System.out.println("Does the stack contains '4'? " + STACK.search("4"));  
        System.out.println("Does the stack contains 'Hello'? " + STACK.search("Hello"));  
    }  
} 

The above program generates the following output.

search-method-example

Another program of Stack.search() method example is listed below.

import java.util.*;  
public class SearchMethodExample2 {  
    public static void main(String[] args) {  
        Stack<Integer> STACK = new Stack<Integer>();  
        STACK.push(8);  
        STACK.push(5);  
        STACK.push(9);  
        STACK.push(2);  
        STACK.push(4);  
  
        System.out.println("The stack is: " + STACK);  
        System.out.println("Does the stack contains '9'? " + STACK.search(9));  
        System.out.println("Does the stack contains '10'? " + STACK.search(10));  
    }  
} 

The above program generates the following output.

search-method-output2

6) Stack removeElementAt() method in Java

The Java.util.Stack.removeElementAt(int index) method is used to remove an element from a Stack from a specific position or index. In this process, the size of the Stack is automatically reduced by one, and all other elements after the removed element is shifted downwards by one position.

This method accepts a mandatory parameter index of integer data type which specifies the position of the element to be removed from the Stack. This method does not return any value.

The complete program of Stack.removeElementAt() method example is listed below.

import java.util.*;  
public class RemoveElementAtExample {  
    public static void main(String args[]) {  
        Stack<Integer> stack = new Stack<Integer>();  
        stack.add(10);  
        stack.add(20);  
        stack.add(30);  
        stack.add(40);  
        stack.add(50);  
        System.out.println("Stack: " + stack);  
        stack.removeElementAt(0);  
        System.out.println("Final Stack: " + stack);  
    }  
} 

The above program generates the following output.

remove-element-example-program

7) Stack remove(int) method in Java

The Java.util.Stack.remove(int index) method is used to remove an element from a Stack from a specific position or index. This method accepts a mandatory parameter index is of integer data type and specifies the position of the element to be removed from the Stack. This method returns the element that has just been removed from the Stack.

The complete program of Stack.remove(int) method example is listed below.

import java.util.*;  
public class RemoveIntExample {  
    public static void main(String args[]) {  
        Stack<Integer> stack = new Stack<Integer>();  
        stack.add(10);  
        stack.add(20);  
        stack.add(30);  
        stack.add(40);  
        stack.add(50);  
  
        System.out.println("Stack: " + stack);  
        int rem_ele = stack.remove(0);  
        System.out.println("Removed element: " + rem_ele);  
        System.out.println("Final Stack: " + stack);  
    }  
} 

The above program generates the following output.

remove-int-element-example

8) Stack removeAllElements() method in Java

The Java.util.Stack.removeAllElements() method is used to remove all components from this Stack and sets its size to zero. The method does not take any argument and does not return any value.

The complete program of Stack.removeAllElements() method example is listed below.

import java.util.*;  
public class RemoveAllElementsExample {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>();  
        stack.add("Welcome");  
        stack.add("To");  
        stack.add("C#Corner");  
        stack.add("4");  
        stack.add("Hello");  
  
        System.out.println("Stack: " + stack);  
        stack.removeAllElements();  
        System.out.println("The final Stack: " + stack);  
    }  
} 

The above program generates the following output.

remove-all-element-example

9) Stack remove(Object) method in Java

The Java.util.Stack.remove(Object o) method is used to remove any particular element from the Stack. This method accepts a mandatory parameter o is of the object type of Stack and specifies the element to be removed from the Stack. Returns True if the specified element is found and removed from the Stack, else False.

The complete program of Stack.remove(Object) method example is listed below.

import java.util.*;  
public class RemoveObjectExample {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>();  
        stack.add("Hello");  
        stack.add("C#Corner");  
        stack.add("10");  
        stack.add("20");  
  
        System.out.println("Stack: " + stack);  
        boolean res = stack.remove("20");  
        System.out.println("Was 20 removed: " + res);  
        System.out.println("Final Stack: " + stack);  
    }  
} 

The above program generates the following output.

remove-object-example-output

10) Stack addAll(int, Collection) method in Java

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. This function accepts two parameters Int index and Collection c.

index: This parameter is of integer data type and specifies the position in the Stack starting from where the elements from the container will be inserted. C: It is a collection of ArrayList. It is the collection whose elements are needed to be appended.

The method returns True if at least one action of append is performed, else False.

The complete program of Stack.addAll() method example is listed below.

import java.util.*;  
import java.util.ArrayList;  
public class AddAllElementExample {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>();  
        stack.add("Hello");  
        stack.add("programmers");  
        stack.add("of");  
        stack.add("C#corner");  
        stack.add("20");  
  
        Collection<String> c = new ArrayList<String>();  
        c.add("A");  
        c.add("best");  
        c.add("Place");  
        c.add("for");  
        c.add("beginners");  
  
        System.out.println("The Stack is: " + stack);  
        stack.addAll(1, c);  
        System.out.println("The new Stack is: " + stack);  
    }  
} 

The above program generates the following output.

add-all-method-example

11) Stack listIterator() method in Java

The listIterator() method of Java.util.Stack class is used to return a list iterator over the elements in this stack (in proper sequence). The returned list iterator is fail-fast. This method returns a list iterator over the elements in this stack (in proper sequence).

The complete program of Stack.listIterator() method example is listed below.

import java.util.*;  
public class ListLteratorExample {  
    public static void main(String[] argv) throws Exception {  
        try {  
            Stack<String> stack = new Stack<String>();  
            stack.add("A");  
            stack.add("B");  
            stack.add("C");  
            stack.add("D");  
  
            System.out.println("Stack: " + stack);  
            ListIterator<String> iterator = stack.listIterator();  
            System.out.println("\nUsing ListIterator:\n");  
            while (iterator.hasNext()) {  
                System.out.println("Value is : " + iterator.next());  
            }  
        } catch (NullPointerException e) {  
            System.out.println("Exception thrown : " + e);  
        }  
    }  
} 

The above program generates the following output.

list-iterator-example-output

12) Stack listIterator(int) method in Java

The listIterator(int) method of Stack Class is used to return a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to previous would return the element with the specified index minus one. The returned list iterator is fail-fast.

This method takes the index of the first element as a parameter to be returned from the list iterator (by a call to next). This method takes the index of the first element as a parameter to be returned from the list iterator (by a call to next). This method throws IndexOutOfBoundsException if the index is out of range (index size()).

The complete program of Stack.listIterator(int) method example is listed below.

import java.util.*;  
public class ListItereatorIntExample {  
    public static void main(String[] argv) throws Exception {  
        try {  
            Stack<String> stack = new Stack<String>();  
            stack.add("A");  
            stack.add("B");  
            stack.add("C");  
            stack.add("D");  
  
            System.out.println("Stack: " + stack);  
            ListIterator<String> iterator = stack.listIterator(2);  
            System.out.println("\nUsing ListIterator" + " from Index 2:\n");  
            while (iterator.hasNext()) {  
                System.out.println("Value is : " + iterator.next());  
            }  
        } catch (IndexOutOfBoundsException e) {  
            System.out.println("Exception thrown : " + e);  
        }  
    }  
} 

The above program generates the following output.

list-iterator-int-example

13) Stack trimToSize() method in Java

The trimToSize() method of Stack in Java trims the capacity of a Stack instance to be the list’s current capacity. This method is used to trim a Stack instance to the number of elements it contains. The method does not take any argument. It does not return any value. It trims the capacity of this Stack instance to the number of the element it contains.

The complete program of Stack.trimToSize() method example is listed below.

import java.util.Stack;  
public class TrimToSizeExample {  
    public static void main(String[] args) {  
        Stack<Integer> stack = new Stack<Integer>();  
        stack.add(10);  
        stack.add(20);  
        stack.add(30);  
        stack.add(40);  
  
        System.out.println("Stack: " + stack);  
        System.out.println("Current capacity of Stack: " + stack.capacity());  
        stack.ensureCapacity(15);  
        System.out.println("New capacity of Stack: " + stack.capacity());  
        stack.trimToSize();  
        System.out.println("Current capacity of Stack" + " after use of trimToSize() method: " + stack.capacity());  
    }  
} 

The above program generates the following output.

trim-to-size-example

14) Stack lastIndexOf(Object, int) method in Java

The Java.util.Stack.lastIndexOf(Object element, int last_index) method is used to the last index of the first occurrence of the specified element in this Stack, searching forwards from the last index, or returns -1 if the element is not found. More formally, returns the lowest last index i such that the last index && Objects.equals(o, get(i))), or -1 if there is no such last index.

This method accepts two parameters:

element of the type of Stack. It specifies the element whose occurrence is needed to be checked in the Stack. last index of the type Integer. It specifies the last index to start searching from.

This method returns the last index or position of the first occurrence of the element in the Stack from the specified last index. Else it returns -1 if the element is not present in the Stack. The returned value is of integer type. This method throws IndexOutOfBoundsException if the specified index is greater than or equal to the current size of this vector.

The complete program of Stack.lastIndexOf() method example is listed below.

import java.util.*;  
public class LastIndexOfExample {  
    public static void main(String args[]) {  
  
        Stack<Integer> stack = new Stack<Integer>();  
        stack.add(1);  
        stack.add(2);  
        stack.add(3);  
        stack.add(10);  
        stack.add(20);  
  
        System.out.println("Stack: " + stack);  
        System.out.println("The 10th occurrence" + " of Geeks is at index: ");  
        try {  
            stack.lastIndexOf("Geeks", 10);  
        } catch (Exception e) {  
            System.out.println(e);  
        }  
    }  
} 

The above program generates the following output.

last-indexof-example

15) Stack toString() method in Java

The toString() method of Java Stack is used to return a string representation of the elements of the Collection.

The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[]. This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation.

The complete program of Stack.toString() method example is listed below.

import java.util.*;  
public class ToStringMethodExample {  
    public static void main(String args[]) {  
        Stack<Integer> stack = new Stack<Integer>();  
        stack.add(10);  
        stack.add(20);  
        stack.add(30);  
        stack.add(40);  
  
        System.out.println(stack.toString());  
    }  
} 

The above program generates the following output.

to-string-example-output

16) Stack size() method in Java

The Java.util.Stack.size() method in Java is used to get the size of the Stack or the number of elements present in the Stack. The method does not take any argument. The method returns the size or the number of elements present in the Stack.

The complete program of Stack.size() method is listed below.

import java.util.*;  
public class SizeOfMethodExample {  
    public static void main(String args[]) {  
        Stack<Integer> stack = new Stack<Integer>();  
        stack.add(10);  
        stack.add(15);  
        stack.add(30);  
        stack.add(20);  
        stack.add(5);  
  
        System.out.println("Stack: " + stack);  
  
        System.out.println("The size is: " + stack.size());  
    }  
} 

The above program generates the following output.

size-of-method-example

17) Stack capacity() method in Java

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. This function accepts a parameter E obj which is the object to be added at the end of the Stack. The method returns an integer value which is the capacity of the Stack.

The complete program of Stack.capacity() method example is listed below.

import java.util.*;  
public class CapacityMethodExample {  
    public static void main(String args[]) {  
        Stack<Integer> stack = new Stack<Integer>();  
        stack.add(10);  
        stack.add(20);  
        stack.add(30);  
        stack.add(40);  
        stack.add(50);  
  
        System.out.println("The Stack is: " + stack);  
  
        System.out.println("Capacity: " + stack.capacity());  
    }  
} 

The above program generates the following output.

capacity-example-output

18) Stack setElementAt() method in Java

The setElementAt() method of Java Stack is used to set the component at the specified index of this vector to be the specified object. The index must be a value greater than or equal to 0 and less than the current size of the vector.

This method throws ArrayIndexOutOfBoundsException if the index is out of range (index = size()) This method throws ArrayIndexOutOfBoundsException if the index is out of range (index = size()).

The complete program of Stack.setElementAt() method is listed below.

import java.util.*;  
public class SetElementAtExample {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>();  
        stack.add("Hello");  
        stack.add("C#Corner");  
        stack.add("5");  
        stack.add("10");  
        stack.add("20");  
  
        System.out.println("Stack:" + stack);  
        stack.setElementAt("programmers", 1);  
        System.out.println("C#Corner replaced with programmers");  
        System.out.println("The new Stack is:" + stack);  
    }  
}

The above program generates the following output.

set-element-at-example

How does Stack push and pop work?

When a Stack is created, it contains no elements. It supports two basic operations called push and pop. The push operation adds an element at the top of the stack, and the pop operation removes an element from the top of the stack.

push-pop-in-stack

Summary

In this article, we learned about the Java Stack class, its constructor and methods, and how to use them in the Java programming language.