Arrays

Arrays are specials variables that store a group of values.

Sometimes when you write a program you might want to store a group or collection of values. Lets say you were writing a program that collects the test scores for the students in a class. Instead of declaring a variable for each test score, you can create one array that stores the whole group of test scores.

Here is an example array that holds 10 test scores:

int testScores[] = new int[10];
testScores[0] = 89;
testScores[1] = 76;
testScores[2] = 92;
testScores[3] = 95;
testScores[4] = 67;
testScores[5] = 99;
testScores[6] = 84;
testScores[7] = 88;
testScores[8] = 91;
testScores[9] = 94;
When you declare an array, you decide the data type of the array. The first line of the example above declares an int array. The brackets [] are used to show that it is an array you are declaring. Also when declaring an array, you use the special new keyword. This is followed by the data type of the array. Last, inside brackets, you put the number of values, or elements, you want to store in the array. The declaration line could be read: declare an integer array that can hold ten integers.

Notice that the ten test scores are numbered 0 through 9. You always start counting arrays at zero.

Conditionals     Forward to Sample Programs