Java Online Compiler
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 latst, that can be retrived first.
Stack class offers following predefined methods.


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();
}
}

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();
}
}

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();
}
}

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();
}
}

Stack Search Method
Which can be used to return index value of the given element otherwise it returns -1

import java.util.*;
class StackSearch
{
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.search(500));
}
}

class Main
{
public static void main(String aargs[])
{
StackSearch d=new StackSearch();
d.list();
}
}