text: Introduction :
  In this article we are going to describe all the methods and constructors of the Stack class. Java provides the easiest way to handle the Data Structure because it provides a direct class for common use. Stack is very powerfull data structure that is commonly used in the implementation of most of the algorithms.
  What is Stack ?
  The Stack represents a last in, first out (LIFO) data structure and linear data structure. A stack has two fundamental operations, called push and pop. the underflow state (which means no items are present in stack to be removed).
  Stack Class
  Stack is a subclass of Vector that implements a standard last-in, first-out stack. The Stack class extends the Vector class.
  Note : when a stack is first initialized (created) than it has no elements.
  Constructor details: This class has only a default constructor; no other constructor.
  public Stack() : Creates an empty Stack.
  Method Details : The Stack class has five methods.
  1-push : This method is used to insert an item into the stack. It pushes an item onto the top of this stack. This has exactly the same effect as the addElement(item) method of the Vector class. It takes one argument as the item. The item is the object that you want to insert.
  Syntaxpublic Object push(Object item)
  2.pop : This method is used to retrieve an element from a stack. It removes the object at the top of this stack and returns that object as the value of this function. It throws the EmptyStackException exception if the stack is empty.
  Syntaxpublic Object pop()
  3.peek : This method is used to retrieve only the top element of the Stack. This method does not remove the top element; it only accesses elements. It throws the EmptyStackException exception if the stack is empty.
  Syntax public Object peek()
  4.empty :This method is used to check whether the stack is empty or not. It's a Boolean method, so it returns true when the stack is empty (no item(s) in the stack) else it return false.
  Syntaxpublic boolean empty()
  5.search :.
  Syntax public int search(Object o)
  Example
  public class StringOperation
  {
  public static void main(String arg[])
  Stringimport java.io.*;
  import java.util.*;
  public class StackExample{
  Stack<Integer> stack;
  String str;
  int num, n;
  public static void main(String[] args){
  StackExample q = new StackExample();
  }
  public StackExample(){
  try{
  stack = new Stack<Integer>();
  InputStreamReader ir = new InputStreamReader(System.in);
  BufferedReader bf = new BufferedReader(ir);
  System.out.print("Enter number of elements : ");
  str = bf.readLine();
  num = Integer.parseInt(str);
  for(int i = 1; i <= num; i++){
  System.out.print("Enter elements : ");
  n = Integer.parseInt(str);
  stack.push(n);
  catch(IOException e){}
  System.out.print("Retrieved elements from the stack : ");
  while (!stack.empty()){
  System.out.print(stack.pop() + " ");
  }
  OUTPUT
  View All