Stack


Stack

It is a linear data structure which can be used to store collection of objects. The 2 important operations performed are push and pop. It follows Last In First Out (LIFO) order. It extends the vector class.

Syntax:

Stack st=new Stack();
OR
Stack=new Stack<>();

Example No.1:

Com.knowledge2life import java.util.Stack; public class Main { public static void main(String[] args) { Stack<Integer> stk= new Stack<>(); boolean result = stk.empty(); System.out.println("Knowledge2life website is empty? " + result); stk.push(78); stk.push(113); stk.push(90); stk.push(120); System.out.println("Rating : " + stk); result = stk.empty(); System.out.println("Is the stack empty? " + result); } }

OUTPUT:

Knowledge2life website is empty? true
Rating : [78, 113, 90, 120]
Is the stack empty? False

Example No.2:

Com.knowledge2life import java.util.Stack; public class Main { public static void main(String[] args) { Stack<Integer> stk= new Stack<>(); boolean result = stk.empty(); System.out.println("Knowledge2life website is empty? " + result); stk.push(4); stk.push(5); System.out.println("Rating : " + stk); } }

OUTPUT:

Knowledge2life website is empty? true
Rating : [4, 5]