Pin It

How to implement Stack collection in Java ?.

Introduction :-
In this section of post we will look into a basic implementation of Stack class in Java. The Stack Class is a very useful data structure used for storing elements/data/information using FILO (First In Last Out) ordering. We can analyze it by observing say bunch of books placed one over the other. So the book kept first over the table or surface will be the last one to read. The book kept on top is one that is first to be used. In the below example stack is governed by two methods called as push and pop. If we want to put an element on the top of the stack we use push method and, if we want to take element from the top of the stack we use pop method.

Program to demonstrate Stack Collection implementation in Java 

package com.hubberspot.stack.example;

/**
 *
 * @author Jontymagicman
 */
 
class Stack {
  int stack[] = new int[10];
  int topOfStack;
  
  Stack() {
    topOfStack = -1;
  }

  void push(int item) {
    if(topOfStack==9) 
      System.out.println("Stack is full.");
    else 
      stack[++topOfStack] = item;
  }

  int pop() {
    if(topOfStack < 0) {
      System.out.println("Stack underflow.");
      return 0;
    }
    else 
      return stack[topOfStack--];
  }
}

public class StackTest {
  public static void main(String args[]) {
    Stack mystack = new Stack();
    
    for(int i=0; i<10; i++) 
        mystack.push(i);
    
    System.out.println("Stack in mystack :");
    for(int i=0; i<10; i++) 
       System.out.println(mystack.pop());

  }
}
  Output of the program :- 





In above example, we have used an array named stack which will hold all the integers in a stack form. Generally, we have used topOfStack variable which initializes the stack array. This variable has the index of the top of the stack.The class StackTest creates one integer stacks, pushes some values onto each, and then pops them off.


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot