-3

So I have an array of objects, 500 to be exact, that i've declared in my code. I ran a for loop from int i = 0 to i < 500; and was expecting all the objects to be initialized or constructed. I checked a member data of array[499] and since it returned true, it was constructed. But for some odd reason 500 gave me an error, which i take as the 500th element was not constructed. Can someone please explain to me the for loop mechanics, and why it didn't construct? I've looked at other posts and saw people doing the same thing and didn'tenter image description here bring up any error. I'm not sure whats the problem with my code, please help. First time SO question. Sorry in advance if i'm asking too simple of a question.

Here's two snippits of my code/execution.

enter image description here

Here's my code incase the link doesn't work:

public class FinalProject {

    public static void main(String[] args) {
        Sample[] library = new Sample[500];

        for(int i = 0; i < library.length; i++)
        {
            library[i] = new Sample();
        }

        System.out.println("Availability of index 1: " + library[499].getAvailability());
     }

}
xenteros
  • 15,586
  • 12
  • 56
  • 91
ArcaneValor
  • 9
  • 1
  • 2

1 Answers1

6

Java is 0 indexed, meaning that array indices start at 0. Thus, your array indices are 0...499, for 500 elements. There is no object at index 500, as it doesn't exist, causing your error.

Iluvatar
  • 1,537
  • 12
  • 13