View RSS Feed

Algorithm and Data Structure

Implementing a Stack in Java

Rate this Entry
by , 02-19-2012 at 08:13 AM (4210 Views)
This post will be explaining the Java’s Stack implementation. Last in first order policy is used in Stack in which one by one elements get inserted in a sequence which could be retrieved later on in reverse order. Use these 2 methods to insert or read the elements to/from the Stack.

• Pop()
• Push()

Code is given below to show the implementation of LIFP stack. Total elements that are needed to be inserted to Stack will be taken and after which it will be asked for those elements which are required to get inserted to Stack.

Java Code: This is the code to explain Stack Implementation in Java
import java.util.*;

public class StackImplement{
  Stack<Integer> stack;
  String str;
  int num, n;
  public static void main(String[] args){
  StackImplement q = new StackImplement();
  public StackImplement(){
  stack = new Stack<Integer>();
  InputStreamReader ir = new InputStreamReader(;
  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 : ");
  str = bf.readLine();
  n = Integer.parseInt(str);
  catch(IOException e){}
  System.out.print("Retrieved elements from the stack : ");
  while (!stack.empty()){
  System.out.print(stack.pop() + "  ");

Submit "Implementing a Stack in Java" to Facebook Submit "Implementing a Stack in Java" to Digg Submit "Implementing a Stack in Java" to Submit "Implementing a Stack in Java" to StumbleUpon Submit "Implementing a Stack in Java" to Google

Tags: java stack Add / Edit Tags