Java Stack Class Tutorial with Examples


The stack is a subclass of vector class in Java. It basically based on LIFO structure that is Last In First Out structure. It has two methods and they are push and pop but as it extends Vector class it gets three more methods search, peek and empty method. By using these methods you can do insert, remove, search etc. operation.

Stack class only has one constructor which is a default constructor. Because of this, you can only create an empty stack.

Commonly used methods

Following are the commonly used methods of Stack Class.

Method description
Object push(Object item) Pushes the object item in the stack and also returns the same object.
Object pop() Return the element on the top of stack by removing it
Object peek() Return the element on the top of stack without removing it
boolean empty() Returns true if stack is empty
int search(Object item) Finds the item in the stack and if found returns its position couting from top of stack otherwise returns -1

Examples

Following programs creates a empty stack and implements five methods provided by stack class.

// Java code for stack implementation 

import java.io.*; 
import java.util.*; 

public class StackTest 
{ 
	// Pushing item on the top of the stack 
	static void stackPush(Stack stack,int item) 
	{ 
		stack.push(item);
		System.out.println("Pushed item: "+item); 
	} 
	
	// Popping element from the top of the stack 
	static void stackPop(Stack stack) 
	{ 
		System.out.println("Popped item: "+(Integer) stack.pop()); 

	} 

	// Displaying item on the top of the stack 
	static void stackPeek(Stack stack) 
	{ 
		Integer item = (Integer) stack.peek(); 
		System.out.println("Stack top item: " + item); 
	} 
	
	// Finds the item inside stack
	static void stackSearch(Stack stack, int item) 
	{ 
		Integer pos = (Integer) stack.search(item); 

		if(pos == -1){
			System.out.println("Item "+ item +" is not found");
		}
		else{
			System.out.println("Item "+ item +" is found at: " + pos);
		}
	}
	
	// check if stack empty
	static void stackEmpty(Stack stack){
	    System.out.println("Is stack empty: "+stack.empty());
	}


	public static void main (String[] args) 
	{ 
		Stack stack = new Stack(); 

		stackEmpty(stack);
		stackPush(stack,5);
		stackEmpty(stack);
		stackPush(stack,6);
		stackPush(stack,7);
		stackPush(stack,8);
		stackPop(stack);
		stackSearch(stack,8);
		stackSearch(stack,5);
		stackSearch(stack,7);
	} 
} 

The output should be:

Is stack empty: true
Pushed item: 5
Is stack empty: false
Pushed item: 6
Pushed item: 7
Pushed item: 8
Popped item: 8
Item 8 is not found
Item 5 is found at: 3
Item 7 is found at: 1