Java Stack Example

In this section you will learn about Stack class in java, how to use Stack in java. Before going into details we should know what is stack class, stack class represent Last In First Out(LIFO) of object.

Java Stack Example

In this section you will learn about Stack class in java, how to use Stack in java. Before going into details we should know what is stack class, stack class represent Last In First Out(LIFO) of object.

Java Stack Example

Java Stack Example

In this section you will learn about Stack class  in java, how to use Stack in java. Before going into details we should know what is stack class, stack  class represent Last In First Out(LIFO) of object. It extend Vector class and provide five operation; push  to enter the element to stack, pop to remove the element from stack, peek to look at the object at the top of the stack without removing it and to check whether stack is empty or not and to check the size of stack size method, and to search the item in the stack and how far it is from top of stack

Example : A Java code how stack is used in java.

import java.util.*;

public class StackDemo
  {
  public static void main(String[] args) 
    {
     Stack st=new Stack();
     System.out.println("stack is empty"+st.capacity());   //return the current capacity of stack 
      System.out.println(st.empty());// To check whether stack is empty or not
      System.out.println(st.push("Hi"));
      System.out.println(st.push("Welcome"));//Inserting value to stack
      System.out.println(st.push("to"));
      System.out.println(st.push("rose india"));
      System.out.println(st.peek());//It will return the first item on the stack.
      System.out.println(st.pop());//Remove the item on top of the stack
      System.out.println(st.search(null));   
      System.out.println(st.size());//return the size of stack
      
    }
  }

In the above example some of the method is used .

Output:  After compiling and executing of above program

Download Source Code