TestScore tests[] = null; // declare the array variable and set it to null
The square brackets indicate that the variable tests is an array. It will reference a list of objects, all of which will be of class TestScore.
Notice that at this point we do not actually have a list. That is the next step.
The number in square brackets indicates how big the array should be. In this case we want the array to be size 5.
Notice that we still do not have any TestScores. That is the third step in creating an array.
The number in the square brackets is the index into the array. In this case we are setting the first element in the array (index 0) to the TestScore that we created with new and calling the constructor that takes two arguments.
What do you think the 2 arguments represent?
Notice that we just write the values tied to a TestScore object inside the new box. Also notice that we have only filled one element in the array.
It is important to start thinking about the details of the types involved.
TestScore tests[] = null; // declare the array variable and set it to null
tests = new TestScore[5]; // allocate the slots in the array
TestScore tests[] = null; // declare the array variable and set it to null
tests = new TestScore[5]; // allocate the slots in the array
tests[0] = new TestScore(19, 20); // create element 0
Let's create two more TestScore elements in our array
TestScore tests[] = null; // declare the array variable and set it to null
tests = new TestScore[5]; // allocate the slots in the array
tests[0] = new TestScore(19, 20); // create element 0
tests[1] = new TestScore(23, 25); // create element 1
tests[2] = new TestScore(47, 50); // create element 2
TestScore tests[] = new TestScore[5]; // declare and allocate the slots in the array
int used = 0;
int i = 0;
String scoreLabel;
tests[0] = new TestScore(19, 20);
tests[1] = new TestScore(20, 20);
tests[2] = new TestScore(23, 25);
used = 3;
System.out.println("The size of our array is " + tests.length +
". We are using " + used + " elements.");
for (i = 0; i < used; i++)
{
scoreLabel = "Score " + (i + 1);
System.out.println(scoreLabel + " is " + tests[i]);
System.out.println(" Letter grade: " + tests[i].getLetterGrade());
}