Initializing Arrays

Individual components of an array are referenced by the array name and by an integer which represents their position in the array. The numbers you use to identify them are called subscripts or indexes into the array.

Subscripts are consecutive integers beginning with 0. Thus the array k above has components k[0], k[1], and k[2]. Since you start counting at zero there is no k[3], and trying to access it will throw an ArrayIndexOutOfBoundsException. You can use array components wherever you'd use a similarly typed variable that wasn't part of an array. For example this is how you'd store values in the arrays above:

k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[17] = 7.5f;
names[4] = "Fred";

This step is called initializing the array or, more precisely, initializing the components of the array. Sometimes the phrase "initializing the array" is used to mean when you initialize all the components of the array.

For even medium sized arrays, it's unwieldy to specify each component individually. It is often helpful to use for loops to initialize the array. Here is a loop which fills an array with the squares of the numbers from 0 to 100.

float[] squares;
squares = new float[101];

for (int i=0; i <= 100; i++) {
   squares[i] = i*i;
}

Two things you should note about this code fragment:

  1. Watch the fenceposts! Since array subscripts begin at zero you need 101 components if you want to include the square of 100.
  2. Although i is an int, it is promoted to a float when it is stored in squares, since squares is declared to be an array of floats.

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified February 3, 1999