Exercise 4

The aim of this exercise is to familiarise yourself with the use of constructors, arrays, exceptions and to gain experience in using a couple more handy Java classes.

The Stack

Your task is to build a Stack class similar to the one you used to implement your postfix calculator. It will be of a fixed size (MAX_STACK) and should include the following data members:

private int    size;
private Object items[] = new Object[ MAX_STACK ];

It should provide the following methods:

public Stack()
public void push( Object item )
public Object pop()
public Object peek()
public boolean empty()
public boolean full()
public String toString()
public removeAllElements()

In this exercise size is the number of elements in the stack (and points at the next location to enter an element since Java arrays start at element 0) and items holds the elements on the stack.

For this exercise you should assume that the functions act as defined below:

You should complete the specification, design and implement the Stack class and undertake testing on the completed class.


Before you leap into the code, you should sit back and write a high level description of the class and a detailed specification of each of the operations. In particular you should think about error conditions (e.g. what happens if you try to pop an element from an empty stack?).

Once you've written and tested it, replace the Stack class you used in your calculator with the one that you've just written (by not importing the java.util one). Does it work?


  1. You may have noticed that there doesn't appear to be anything you can do if someone tries to pop an element off an empty stack, other than print out a warning message. The java.util.Stack however throws an exception when this case occurs. Try modifying your code to throw new java.util.EmptyStackException(); instead.

    Unlike your stack, the java.util.Stack doesn't have a fixed size, so if you want to throw a FullStackException you'll have to make your own. To do this, you can save this chunk of code to a file called FullStackException.java:

     * This exception should be thrown when an operation on
     * a stack doesn't succeed because the stack is already
     * full to capacity.
     * @author (c) Andy Wood ... 1997
    public class FullStackException extends RuntimeException
      public FullStackException()
  2. Try reimplementing your stack using a java.util.Vector instead of your array of Objects. Since a vector is a "growable array" you will not have to worry about your stack getting too full (unless you use up all the memory in your computer).
  3. For another exercise that uses some useful Java classes, try counting words in essays.