• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Collection Framework Stack


Stack Class :
Stack is a predefined package in java.util package .It allows duplicate elements along with unique elements and it works on last in first out manner.That means the element which inserted at last, that can be retrieved first. Stack class offers the following predefined methods.
Stack Methods
1.Push
2.Pop
3.Peek
4.Empty
5.Search


Key Points

Image






Stack Push Method:
It is used to push a new element on top of stack




Import  java.util.*;	
	class StackPush
	{
	void list()
	{
	Stack<Integer> al=new Stack<Integer>();
	al.push(20);
	al.push(10);
	al.push(30);
	al.push(40);
	al.push(50);
	System.out.println("The List Items Are "+al);
	}
	}
	class Main
	{
	public static void main(String aargs[])
	{
	StackPush d=new StackPush();
	d.list();
	}
	}





                                

Output:

Stack Pop Method
Which will be used to remove the element from the top of stack.


import java.util.*;	
	class StackPop
	{
	void list()
	{
	Stack<Integer> al=new Stack<Integer>();
	al.push(20);
	al.push(10);
	al.push(30);
	al.push(40);
	al.push(50);
	System.out.println("The List Items Are "+al);
	al.pop();
	System.out.println("After Poping The List Items Are "+al);
	}
	}
	
	class Main
	{
	public static void main(String aargs[])
	{
	StackPop d=new StackPop();
	d.list();
	}
	}


Output:

Stack Peek Method
It returns the type of the stack element.


import java.util.*;	
	class StackPeek
	{
	void list()
	{
	Stack<Integer> al=new Stack<Integer>();
	al.push(20);
	al.push(10);
	al.push(30);
	al.push(40);
	al.push(50);
	System.out.println("The List Items Are "+al);
	
	System.out.println(al.peek());
	}
	}
	
	class Main
	{
	public static void main(String aargs[])
	{
	StackPeek d=new StackPeek();
	d.list();
	}
	}

 

Output:

Stack Empty Method
It returns true in the given stack is empty otherwise false.


import java.util.*;	
	class StackEmpty
	{
	void list()
	{
	Stack<Integer> al=new Stack<Integer>();
	al.push(20);
	al.push(10);
	al.push(30);
	al.push(40);
	al.push(50);
	System.out.println("The List Items Are "+al);
	
	System.out.println(al.empty());
	}
	}
	
	class Main
	{
	public static void main(String aargs[])
	{
	StackEmpty d=new StackEmpty();
	d.list();
	}
	}


Output: