Example of Java Stack Program

Stack is like a bucket we you can enter objects and retrieve it.

Example of Java Stack Program


Stack is like a bucket we you can enter objects and retrieve it. Here in the example describes the methods to prepare an example of Java stack program. The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector and implements Cloneable, Collection, List, Serializable interfaces. We mostly use push and pop operations.

In this example we are using two methods of Stack.

push(Object item): It pushes an item onto the top of this stack.

pop(): Removes the object from the top of this stack and returns that object as the value of this function. It throws EmptyStackException if the stack is empty.

Code of the program is given below

import java.util.*;

public class StackDemo{
  public static void main(String[] args) {
  Stack stack=new Stack();
  stack.push(new Integer(10));
  System.out.println("The contents of Stack is" + stack);
  System.out.println("The size of an Stack is" + stack.size());
  System.out.println("The number poped out is" + stack.pop());
  System.out.println("The number poped out is " + stack.pop());
  //System.out.println("The number poped out is" + stack.pop());
  System.out.println("The contents of stack is" + stack);
  System.out.println("The size of an stack is" + stack.size());

Output of this example is given below:

The contents of Stack is[10, a]
The size of an Stack is2
The number poped out isa
The number poped out is 10
The contents of stack is[]
The size of an stack is0
Hello World!

Download this example


Share on Google+Share on Google+

Example of Java Stack Program

Posted on: June 7, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Example of Java Stack Program   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
April 15, 2011
Technical Programming

how to create stack class
June 25, 2011

Thank you very much for this examples
July 2, 2011
Version 1.5

Hi, could you please update this example for Java 1.5 with generics. Thanks in advance.
October 25, 2011
teststring stack

in some sample of this program i notice that i can't find specific output why it only appear those unclear elements of this stack
February 16, 2012

why is it wrong when it comes to Stack stack=new Stack(); ?
March 5, 2012
data structures

add more
anuj anand
August 21, 2012

this website is very helpful form me......thank's....rose india
October 10, 2012

September 7, 2013
import java.util.Stack

For Stack class
saraswathi kalapala
December 10, 2012
print stack elements in java

please tell