Java Stack Example


Java StackViews 3502

What is a Java Stack class?

A Java stack class implementation is based on the stack data structure. It follows the concept of the Last-In-First-Out(LIFO) concept which means the element that we insert last will be removed first. In other words, we can delete elements only from the top of the stack. The Java Stack class extends the Vector class and hence imports the methods of the Vector class as well. In this tutorial, we will learn about the Java stack class and methods with stack implementation in Java with examples and its different operations.

Working of a Java Stack data structure

The stack class in Java has two main operations to insert and remove elements. The push() method inserts an element and the pop() method deletes an element. Both the operations occur from the top of the stack.

The below diagram represents the working of a stack data structure in java.

Java stack implementation

Push operation:

As we insert each element into a stack using the push method, the last inserted element will always be on the top. It keeps adding elements on top of the older element. For example, first, we insert 10, then 20. In this case, 20 will be on top of 10, and so on.

Java stack implementation

Pop operation:

The pop method removes the latest element that we insert from the top of the stack. This follows the concept of LIFO which is Last-In-First-Out. For example, if we have 5 elements 10,20,30,40 and 50. Hence when we use the pop() method, it removes the value 50 first since that is the topmost element present in the stack.

Java stack operations

How to create a stack in Java

We can create an empty stack using the default constructor stack().  To implement the stack data structure, we need to import the java.util.stack package.

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

E denotes the generics type.

Stack methods in Java

Below are the methods that are part of the Stack class.

MethodsDescription
boolean empty()Checks if the stack is empty
Returns true if stack is empty else it returns false
Integer peek()Returns the last element inserted which is on the top of the stack
Integer pop()Returns and removes the last element inserted which is on the top of the stack
Integer push(Integer e)Pushes or inserts an element to the stack
int search(Object o)Searches for the specified element in the stack and returns the distance from the top of the stack

Below are the methods in the Vector class. The stack class imports all the methods of the Vector class as well.

MethodDescriptionParameter
Boolean add(Object e)Adds the specified element to the end of the vectore - the element to be added.
Return value - True
void add(int index, Object e)Adds the element to the specified index. If the index already contains an element, it is shifted to the rightindex- the index at which the element needs to be inserted
e - the element which needs to be inserted
Boolean addAll(Collection c)Adds a collection of specified elements to the vectorc - collection of elements to be added
Return value - true
Boolean addAll(int index, Collection c)Adds a collection of elements at the specified index. If the index already contains element, it is subsequently shifted to the rightindex - index at which the elements needs to be added
c - collection of elements to be added
Return value - True
void addElement(Object obj)Adds the specified component to the vectorobj - the component to be added
int capacity()Returns the current capacity or size of the vector
void clear()Removes all elements from the vector and becomes empty
Object clone()Returns a clone of the vector where the copy contains a reference to the clone of the internal data array
Boolean contains(Object o)Checks if the vector contains the specified elementReturn value - true if the list contains the element
Boolean containsAll(Collection c)Checks if the vector contains all the elements in the collectionReturn value - true if the list contains all the elements
void copyInto(Object[] anArray)Copies the contents of the vector into the specified arrayanArray - array that has to hold the content of the vector
Object elementAt(int index)Returns the object at the specified index
Enumeration elements()Returns an enumeration of all the components in the vector where start index is at 0
void ensureCapacity(int minCapacity)Ensures that the vector can hold the least minimum capacity specified
Boolean equals(Object o)Compares if the vector contains all the specified elements in the exact orderReturn value - true if object elements match with the list
Object firstElement()Returns the first component at index 0
void forEach(Consumer action)Performs the given action for the element in the vector in an iteration.
Object get(int index)Returns the element at the specified indexindex - the position of the element to be retrieved
int indexOf(Object o)Fetches the index of the first occurrence of the specified elemento - The element to be identified
Return value - index value
int indexOf(Object o, int index)Returns the index of the first occurence of the element specified starting from the index mentionedo - The element to be identified
index - start index of the search
void insertElementAt(Object o, int index)Inserts the specified object as component to the vector at the specified indexo - The element to be identified
index - index at which element has to be inserted
boolean isEmpty()Checks if the vector is empty
Iterator iterator()Returns an iterator over the elements in the vector
Object lastElement()Returns the last element in the vector
int lastIndex(Object o)Returns the last occurrence of the specified element. If not present, returns -1
int lastIndex(Object o, int index)Returns the last occurrence of the specified element searching backwards from the specified index. If not present, returns -1
ListIterator listiterator()Returns the listiterator over the elements in the vector
ListIterator listiterator(int index)Returns the listiterator over the elements in the vector from the specified index
Object remove(int index)Removes the element at the specified index from the vectorReturn value - the element that is removed
boolean remove(Object o)Removes the specified element from the vectorReturn value - true if removed
Boolean removeAll(Collection c)Removes all the elements of the Collection from the vectorc - Collection elements
void removeAllElements()Removes all components from the vector and sets the size to 0
boolean removeElement(Object o)Removes the specified element from the vectorReturn value - true if removed
void removeElementAt(int index)Removes or deletes the component at the specified index
boolean removeIf(Predicate filter)Removes all elements that satisfies the given predicatefilter - condition to be applied
Boolean retainAll(Collection c)Retains all the elements specified in collection in the vector. Other elements will be removedc - collection of elements that has to be retained
Return value - true if the vector changed due to the method called
Object set(int index, Object o)Replaces the element at the specified index with the object passedo - the element to be replaced
index - index of the element
Return value - Returns the element which was previously at the specified index
void setElementAt(Object o, int index)Sets the component at the specified index by discarding the old valueo - element to be set
index - index at which the element has to be updated
void setSize(int newsize)Sets the size of the vector with the specified valuenewsize - size of the vector
int size()Returns the number of components in the vector
void sort(Comparator c)Sorts the elements in the vector based on the comparatorc - comparator value
List sublist(int fromIndex, int toIndex)Retrieves the part of the list based on start and endIndexfromIndex - position from which the sublist has to be retrieved (included)
toIndex - the index until which the sublist has to be retrieved (excluded)
Object[] toArray()Returns an array of elements in the vector
void trimToSize()Trims the capacity of the vector to be the current capacity size

Java Stack examples

Below are the various Java stack examples of different stack operations in java.

Example: push() – Adding elements to a stack

The below example illustrates how to insert an element to a Java stack using the push() method. This is equivalent to the add() method of the Vector class. Each time it adds the element, it goes to the bottom of the stack so that the last inserted element will be on the top.

import java.util.Stack;

public class StackDemo {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    s.push(50);
    
    System.out.println("Elements in stack: " + s);
  }

}
Elements in stack: [10, 20, 30, 40, 50]

Example: pop() – Remove elements from a stack

The below example shows how to delete elements from the stack. It removes the latest element from the top of the stack first. Hence the first pop() method returns 50 which is the last element that is inserted and followed by the element 40 for the second pop() method.

import java.util.Stack;

public class StackDemo {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    s.push(50);
    
    System.out.println("Elements in stack: " + s);
    
    int x = s.pop();
    System.out.println("Element removed from stack: " + x);
    
    x = s.pop();
    System.out.println("Element removed from stack: " + x);
  }

}
Elements in stack: [10, 20, 30, 40, 50]
Element removed from stack: 50
Element removed from stack: 40

Example: search() method

The search() method searches for the specific element and returns the position starting from the top of the stack. In this example, element 30 is present in the 3rd position and element 40 in the 2nd position.

import java.util.Stack;

public class StackDemo {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    s.push(50);
    
    System.out.println("Elements in stack: " + s);
    
    System.out.println("The index of element 30 using search method: " + s.search(30));
    System.out.println("The index of element 40 using search method: " + s.search(40));
  }

}
Elements in stack: [10, 20, 30, 40, 50]
The index of element 30 using search method: 3
The index of element 40 using search method: 2

Example: peek() method

The peek() method returns the last inserted element which is the topmost element. This method only retrieves the value and does not remove it from the stack.

import java.util.Stack;

public class StackDemo {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    s.push(50);
    
    System.out.println("Elements in stack: " + s);
    System.out.println("Element returned using the peek() method: " + s.peek());
    
  }

}
Elements in stack: [10, 20, 30, 40, 50]
Element returned using the peek() method: 50

Example: Iterate through Java stack elements

We can iterate through all elements in the Java stack using the iterator method present in the Vector class. The below example shows how to iterate a stack.

import java.util.Iterator;
import java.util.Stack;

public class StackDemo {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    s.push(50);
    
    System.out.println("Elements in stack: " + s);
    
    Iterator<Integer> i = s.iterator();
    while(i.hasNext())
      System.out.println(i.next());
    
  }

}
Elements in stack: [10, 20, 30, 40, 50]
10
20
30
40
50

Example: Clear a stack check if empty

Below is an example to clear the elements in the stack using the clear() method and check if the attack is empty using the isEmpty() method. Initially, whenever we create a stack, it will be empty. This is also called an empty stack.

import java.util.Iterator;
import java.util.Stack;

public class StackDemo {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    s.push(50);
    
    System.out.println("Elements in stack: " + s);
    System.out.println("Is stack empty: " + s.isEmpty());
    
    s.clear();
    System.out.println("Elements in stack after clear method: " + s);
    System.out.println("Is stack empty: " + s.isEmpty());
    
  }

}
Elements in stack: [10, 20, 30, 40, 50]
Is stack empty: false
Elements in stack after clear method: []
Is stack empty: true

Example: Convert Java List to stack

We can convert a Java List to stack by adding a collection of list elements to stack using the addAll() method.

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class ListToStack {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    List<Integer> l = new ArrayList<Integer>();
    
    l.add(10);
    l.add(20);
    l.add(30);
    l.add(40);
    l.add(50);
    
    s.addAll(l);
    System.out.println("Elements in stack from List: " + s);

  }

}
Elements in stack from List: [10, 20, 30, 40, 50]

Example: Convert array to a stack

In the below example, we add array elements to a stack using the push() method.

import java.util.Stack;

public class ArrayToStack {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    int[] num = {10,20,30,40,50};
    
    for(int i : num)
      s.push(i);
    
    System.out.println("Array elements in stack: " + s);
  }

}
Array elements in stack: [10, 20, 30, 40, 50]

Example: Convert stack to an array

We can also convert a stack to an array using the toArray() method as in the below example.

import java.util.Stack;

public class StackToArray {

  public static void main(String[] args) {
    Stack<Integer> s = new Stack<Integer>();
    s.push(10);
    s.push(20);
    s.push(30);
    
    System.out.println("Elements in stack: " + s);
    
    Object[] arr = s.toArray();
    System.out.println("Elements in Array: ");
    for(int i=0;i<arr.length;i++)
      System.out.print(arr[i] + " ");
  }

}
Elements in stack: [10, 20, 30]
Elements in Array: 
10 20 30

Conclusion

In this tutorial, we have seen how to use the Java stack class and methods along with stack implementation and examples.

Reference

Translate »