Arrays

This chapter introduces arrays, a common multi-dimensional data structure used to store data of the same type. (Note that a class is a "data type" in this sense.) Arrays have some number of dimensions and a number of elements in each dimension. These are established when the array is created. The range of the array's index in each dimension goes from zero to the number of that dimension's elements minus one. A for loop is commonly used to initialize, manipulate, and access the values in an array. Here, we treat one-dimensional arrays, sometimes called vectors.

7. Array Initialization


Answer:

int[] scores = new double[25];            
      • scores[ 0 ]       OK
      • scores[ 1 ]       OK
      • scores[ -1 ]       illegal
      • scores[ 10]       OK
      • scores[ 25 ]       illegal
      • scores[ 24 ]       OK
      • scores[ 1.2]       illegal
      • scores [2]           OK
      • scores [ 4 ]       OK

Notice that there may be spaces between the reference variable name and the first bracket [ . Usually this is not done, however.

Array Initialization

Annotation 2020-03-26 194139

Lacking any other information, the cells of an array are initialized to the default value for their type. Each cell of a numeric array is initialized to zero.

Each cell of an array of object references is initialized to null. (Arrays of object references are discussed in an upcoming chapter.)

Of course, the program can assign values to cells after the array has been constructed. In the following, the array object is constructed and each cell is initialized to 0. Then some assignment statements explicitly change some cells:

class ArrayEg1
{
  public static void main ( String[] args )
  {
    int[] stuff = new int[5];

    stuff[0] = 23;
    stuff[1] = 38;
    stuff[2] = 7*2;

    System.out.println("stuff[0] has " + stuff[0] );
    System.out.println("stuff[1] has " + stuff[1] );
    System.out.println("stuff[2] has " + stuff[2] );
    System.out.println("stuff[3] has " + stuff[3] );
    System.out.println("stuff[4] has " + stuff[4] );
  }
}


Question 7:

What does the program write?

stuff[0] has
stuff[1] has
stuff[2] has
stuff[3] has
stuff[4] has