Program To Demonstrate Stack Collection Implementation In Java

Introduction :-

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) {
System.out.println("Stack is full.");
stack[++topOfStack] = item;

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

public class StackTest

public static void main(String args[]) {
Stack mystack = new Stack();

for(int i=0; i<10; i++)

System.out.println("Stack in mystack :");
for(int i=0; i<10; i++)


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.




For more of such hot topics read my other posts here :

Visit my new website

Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 121 0

Please login to comment on this post.
There are no comments yet.
How Garbage Collection Works In Java ?
Exception Handling In Java : Checked And Unchecked Exceptions