Stack Class in Java : a complete tutorial

Stack is a child class of vector specially designed for inserting element only in LIFO (Last In First Out) order. That means which element is inserted last will be removed first and which element was inserted first will be removed at last. So Stack is also works in FILO (First In Last Out) structure, but we will use LIFO as it is used globally.

Features of Stack class in Java

1)Stack is the child class of vector.
2)Stack follows the LIFO concept ( Last in First Out ).
3)Stack has only one constructor.
4)Stack inherit all methods of vector class.

Constructors in Stack class in JAVA

There is only one constructor in Stack.

1 ) Stack()  -> It will create the empty stack object.

example : Stack stck = new Stack();

Stack Class in JAVA Diagram

stack java


Methods in Stack : 5 methods in stack

There are a number of methods in Stack operations:

  • Object push(Object obj) : This method is used to insert element in the Stack. push() will insert the element after the last inserted element.
  • Object pop() : This method is used to remove element from the Stack. pop() method will return the last inserted element from the Stack after successful removal of that element.
  • Object peek() : This method is used to check the Top of the Stack (TOP) i.e. the last inserted element in the Stack without removing it from the Stack.
  • boolean empty() : This method is used to check if the Stack is empty or not. If the Stack is empty this method will return ‘True’ and ‘False’ otherwise.
  • int search(Object obj) : This method is used to check if an object is present in the Stack or not. If the object is present then this function will return its offset value and if the object is not there in the Stack this method will return the value -1.

Java code to demonstrate stack methods

// stack constructors and method
import java.util.*;

public class collectiontutorials {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 
 
 
 // stack constructors and method
 Stack stck = new Stack(); // create stck empty stack object
 stck.push("a");// add 1st element
 stck.push("b");// add 2nd element
 stck.push("c");// add 3rd element
 stck.push("d");// add 4th element
 System.out.println(stck);// output -> [a, b, c, d]
 
 stck.pop(); // removes the top element of stack
 System.out.println(stck);// [a, b, c] -> d is removed
 
 stck.peek();
 System.out.println(stck.peek());// output -> [c]
 System.out.println(stck);// [a, b, c] -> none is removed
 
 System.out.println(stck.empty());// output -> false as stack is not empty
 
 System.out.println(stck.search("b"));// output -> 2 -> 2 is offset of element b
 System.out.println(stck.search("y"));// output -> -1 -> y is not present in stack

}
}
// 

so this is all about the stack class in Java. If you have any questions please leave in below comment section.