Stack in Java

  • The stack is a linear data structure that is used to store the collection of objects.
  • It is based on Last-In-First-Out (LIFO)
  • Stack class provides different operations such as push, pop, search, etc.
  • Stack extends Vector i.e Stack is Threadsafe and underlying data structure is ArrayList(Array)

Example :

package java8;

import java.util.Stack;

public class StackDemo {
	public static void main(String[] args) {
		Stack<String> animals= new Stack<>();
		animals.push("Dog");
        animals.push("Horse");
        animals.push("Cat");

        System.out.println("Stack: " + animals);
        // Remove element stacks
        String element1 = animals.pop();
        System.out.println("Removed Element: " + element1);
        
     // Access element from the top
        String element2 = animals.peek();
        System.out.println("Element at top: " + element2);
        
     // Search an element
        int position = animals.search("Horse");
        System.out.println("Position of Horse: " + position);
        
        // Check if stack is empty
        boolean result = animals.empty();
        System.out.println("Is the stack empty? " + result);
	}
}

Use ArrayDeque Instead of Stack

The Stack class provides the direct implementation of the stack data structure. However, it is recommended not to use it. Instead, use the ArrayDeque class (implements the Deque interface) to implement the stack data structure in Java.

Leave a Comment