Java ArrayIndexOutOfBoundsException

Software

Starbucks cups

Because I'm studying full time again after having a leave of absence and studying part time, all my classes (get it!?) are out of whack. For example I've started Java again this semester and I'm hopelessly rusty! One problem I'm having is creating an object array, assigning objects to it, then attempting to use methods from the objects in a loop.

Simple, right? Whenever I try, I get the following error:

Exception in thread "main" 
java.lang.ArrayIndexOutOfBoundsException: [x]

I'm not attempting to access objects that don't exist in the array, I'm using the array.count() method to only loop through the ones I know exist. Still, the error persists and it's driving me crazy!

Here's the problem reproduced in a very basic example. I'm creating a Market object, adding a series of Stall objects (which number to less than 10!), then attempting to read the toString() methods for each Stall in the Market.

Stall.java

public class Stall {
   String name = "Vacant";
   public Stall(String name) {
      this.name = name;
   }
   public String toString() {
      return name;
   }
}

Market.java

public class Market {
   private Stall stalls[] = new Stall[10];
   public void addStall(Stall a) {
      stalls[stalls.length] = a;
   }
   public String toString() {
      String toReturn = "";
      for (int count = 0; count < stalls.length; count++) {
         toReturn += (stalls[stalls.length] + " ");
      }
      return toReturn;
   }
}

TestMarket.java

public class TestMarket {
  public static void main(String[] args) {
    Stall coffeeBean = new Stall("Coffee Bean and Tea Leaf");
    Stall starbucks = new Stall("Starbucks");
    Market rundleMall = new Market();
    rundleMall.addStall(coffeeBean);
    rundleMall.addStall(starbucks);
    System.out.println(rundleMall);
  }
}

The thing I'm doing wrong is probably breathtakingly obvious, but I've been staring at this for hours and can't figure it out. The only way I've been able to fix it is to wrap the inside of each for loop in a try statement and catch ArrayIndexOutOfBoundsException which is hardly an ideal solution!

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.