Stack class

In this article, we will discuss Stack class in detail. Stack is a legacy class introduced in Java 1.0 version which works in Last-In First-Out order (LIFO order) and most of its methods are synchronized i.e.; thread-safe



  • Stack is a sub-class of Vector (i.e.; Stack extends Vector)
  • All properties are same as that of Vector class
  • Its data structure is designed in such a way that elements added last to the Stack will be returned first
  • That is, it follows Last-In First-Out order
  • Present in java.util package and extends java.util.Vector class


Stack constructors:

Stack s = new Stack();

  • Stack defines default constructor which creates an empty Stack object


Stack methods:

Stack specific methods

 Stack methods Description
Object push(Object obj); add/inserts new element/object into stack
Object pop(); removes and return top of the stack
Object peek(); returns top of the stack (just returns but doesn’t remove unlike pop() operation
boolean empty(); check whether invoking stack is empty or not
returns true, if stack is empty; otherwise, false
int search(Object obj) searches specified element/object from invoking stack

returns offset from top of the stack, if element is available; otherwise returns -1, if element not available


Stack examples:


import java.util.Stack;

public class StackPushAndPop {

	public static void main(String[] args) {

		// creating Stack object of type String
		Stack<String> stk = new Stack<String>();

		// adding elements to Stack object
		stk.push("Sundar Pichai");
		stk.push("Satya Nadella");  
		stk.push("Shiv Nadar");  
		stk.push("Shantanu Narayen");
		stk.push("Francisco D’Souza");

		System.out.println("Iterating Stack values\n");

		// Iterating using enhanced for-loop
		for(String str : stk){

		// peeking top of the stack - doesn't remove
		String peekStr = stk.peek();
		System.out.println("\n\nElement peeked at top "
				+ "of the Stack : " + peekStr);

		// removing top element of the Stack
		String poppedStr = stk.pop();
		System.out.println("\n\nElement removed at top "
				+ "of the Stack : " + poppedStr);

		// check whether Stack is empty
		boolean isStackEmpty = stk.empty();
		System.out.println("\n\nWhether Stack is Empty : " 
				+ isStackEmpty);

		// to print all values of Stack
		System.out.println("\n\nStack values after removing "
				+ "top of the Stack \n" + stk);



Iterating Stack values

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Francisco D’Souza

Element peeked at top of the Stack : Francisco D’Souza

Element removed at top of the Stack : Francisco D’Souza

Whether Stack is Empty : false

Stack values after removing top of the Stack 
[Sundar Pichai, Satya Nadella, Shiv Nadar, Shantanu Narayen]



Note: All methods of Stack are synchronized hence it is thread-safe




Happy Coding !!
Happy Learning !!