Core Java Tutorial

Core Java Tutorial

Stack Example Program in Java

Stack in Java:

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.

Alternativley you can use Deque for more operation.

Example:

package com.candidjava.core;


import java.util.Stack;


public class StackExample {


 public static void main(String[] args) {

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

  st.push("hai");

  st.push("123");

  st.add("mathan");

  st.add("lst");

  st.add("mathan");

  st.add("lst");

  st.add("ramya");

  st.add("suji");

  st.add("ravathi");

  st.add("sri");


  System.out.println("stack .. " + st);

  System.out.println("size ... " + st.size());


  st.pop();


  System.out.println("stack .. " + st);

  System.out.println("size ... " + st.size());


 }

}

 

Output:
stack ..  [hai, 123, mathan, lst, mathan, lst, ramya, suji, ravathi, sri]
size ... 10
stack ..  [hai, 123, mathan, lst, mathan, lst, ramya, suji, ravathi]
size ... 9