Write a program to implement Stack using array in Java

Below program illustrates how to implement Stack using array in Java:

public class StackUsingArray {
 
	public static void main(String[] args) {
		MyStack stk = new MyStack(4);
		stk.push(1);
		stk.push(2);
		stk.push(3);
		stk.push(4);
		System.out.print("Stack after pushing all items: ");
		stk.print();
		
		System.out.println();
		stk.pop();
		System.out.print("Stack after popping out 1 item: ");
		stk.print();
		System.out.println();
		System.out.println("Element at peek: " + stk.peek());
	}
 
}
 
class MyStack {
	
	private int max;
	private int top;
	private Object[] data;
	
	public MyStack() {
		max = 100;
		data = new Object[max];
		top = -1;
		
	}
	
	public MyStack(int capacity) {
		max = capacity;
		data = new Object[max];
		top = -1;
	}
	
	public boolean push(Object item) {
		if(top < max) {
			data[++top] = item;
			return true;
		} else {
			System.out.println("Stack overflow!");
			return false;
		}
	}
	
	public Object pop() {
		Object item = null;
		if(top == -1) {
			System.out.println("Stack underflow!");
		} else {
			item = data[top];
			data[top] = null;
			top--;
		}
		return item;
	}
	
	public boolean isEmpty(){
		if(top == -1) {
			return true;
		} else {
			return false;
		}
	}
	
	public Object peek() {
		if(top != -1) {
			return data[top];
		}
		return null;
	}
	
	public void print() {
		for(int i=0; i <= top; i++) {
			System.out.print(data[i] + " ");
		}
	}
}

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.