user519670 user519670 - 1 year ago 69
Java Question

java stack reading from an array throws ArrayIndexOutOfBoundsException

I need to fill a stack from an array, then print out the elements in order and then again reversing the order. What I'm having problems with is I'm getting an ArrayIndexOutOfBoundsException and cant figure out where it is coming from. I have tried running through the debug and it appears as I'm popping off elements it never reaches the last element. Below is my code:

public class arrayStack {

private int top;
private String[] storage;

public arrayStack(int capacity)
storage = new String[capacity];
top = -1;

public boolean isEmpty() {
return (top == 0);

String peek() {
return storage[top];

String pop() {
return storage[top];

public void push(String str) {
storage[top] = str;


public class StackMain {

public static void main(String[] args) {
//int j = 5;
String[] list = new String[5];

list[0] = "Beware";
list[1] = "The";
list[2] = "Ides";
list[3] = "Of";
list[4] = "March";

arrayStack stack = new arrayStack(5);

for(int i = 0; i < list.length; i++)

for(int j = 0; j < list.length; j++)



tom tom
Answer Source

In pop(), you need to return the item that was popped, which is the item at the index of the old value of top. Cleanest way is to change the function to

String pop() {
    return storage[top--];

You also need to change isEmpty() to return (top == -1). You could also change the implementation to use size (the number of elements) instead of top (the index of the highest element) like others mentioned.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download