dsa

Java Stack

In this tutorial, we will learn about the Stack, its contructors and methods and how to implement it in Java.

Java Collection frameworks provide Stack class which works on stack data structure.It works on the principle of Last-In-First-Out(LIFO).It extends Vector class for better performance.

Constructors in the Stack

This class supports one default constructor which creates an empty stack.

Methods of Stack

Apart from the methods inherited from its parent class/interface ,it has following methods :

MethodsDescription
Object push(Object element) : Pushes an element on the top of the stack.
Object pop() : Removes and returns the top element of the stack. An ‘EmptyStackException’ exception is thrown if we call pop() when the invoking stack is empty.
Object peek() : Returns the element on the top of the stack, but does not remove it.
boolean empty() : It returns true if nothing is on the top of the stack. Else, returns false.
int search(Object element) : It determines whether an object exists in the stack. If the element is found, it returns the position of the element from the top of the stack. Else, it returns -1.

Example


import java.util.Stack;
class Main
{
    	public static void main(String[] args) 
	{
        	Stack<String> city= new Stack<>();

        	// Adding elements to Stack
        	city.push("Pune");
        	city.push("Jabalpur");
        	city.push("Banglore");
        	city.push("Jharkhand");
        	System.out.println("Stack: " + city);
	
		// Removing elements from Stack
		String element1 = city.pop();
        	System.out.println("Removed Element: " + element1);

		//printing the element at the top of stack
		String element2 = city.peek();
        	System.out.println("Element at top: " + element2);

		// Searching an element in the stack
        	int position = city.search("Jharkhand");
        	System.out.println("Position of Jharkhand: " + position);

		// Check if stack is empty
        	boolean result = city.empty();
        	System.out.println("Is the stack empty? " + result);
    	}
}

Output:

Stack: [Pune, Jabalpur, Banglore, Jharkhand]                                                                                   
Removed Element: Jharkhand                                                                                                     
Element at top: Banglore                                                                                                       
Position of Jharkhand: -1                                                                                                      
Is the stack empty? false  

Note: The Stack class in Java is a legacy class and inherited from Vector class in Java. It is a thread safe class and hence involves overhead when we do not need thread safety. It is recommended to use ArrayDeque for stack implementation as it is more efficient in a single threaded environment.