IntStack implementation, includes a separate class StackException.

// Stack implementation with arrays

public class IntStack {
    private int capacity = 1000;
	private int [] items = new int [capacity];
	private int top = -1;
	
	public IntStack() {
		// do nothing	
	}
	
	public boolean isEmpty() {
		return top == -1;	
	}
	
	public int pop() throws StackException {
		if(!isEmpty()) {
			int n = items[top];
			top--;
			return n;			
		}
		else throw new StackException("Stack underflow");
	}
	
	public void push(int n) throws StackException {
		if (top == capacity - 1) 
		    throw new StackException("Stack overflow");
		top++;
		items[top]=n;
	}
}



public class StackException extends RuntimeException {
	public StackException(String s) {
		super(s);
	}
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.