Java Free Tutorial

Web based School


Chapter 9

Storing Information with Arrays

No one benefits more from the development of the computer than Santa Claus. For centuries, humankind has put an immense burden on him to gather and process information. Old St. Nick has to keep track of the following things:

  • Naughty children

  • Nice children

  • Gift requests

  • Homes with impassable chimneys

  • Women who want more from Santa than Mrs. Claus is willing to let him give

  • Countries that shoot unidentified aircraft first and ask questions later

Computers must have been a great boon at the North Pole because they are ideal for the storage, categorization, and study of information.

The most basic way that information is stored in a computer program is by putting it into a variable. However, this method is limited to relatively simple usage. If Santa had to give each naughty child his or her own variable name, he'd be working on the program for the next 12 holiday seasons at least, to say nothing of the effect on his jolly disposition or his carpal tunnel nerves. The list of naughty children is an example of a collection of similar information. Each child's name is a string of text or some kind of Santa Information System ID number. In order to keep track of a list of this kind, you can use arrays.

Arrays are groups of related variables that share the same type. You can have arrays of any type of information that can be stored as a variable. Arrays can be used to keep track of more sophisticated types of information than a single variable, but they are almost as easy to create and manipulate as variables are.

The following topics will be covered during this hour:

  • Creating an array

  • What a dimension of an array is

  • Giving a value to an array element

  • Changing the information in an array

  • Making multidimensional arrays

Creating Arrays

Arrays are variables that are grouped together under a common name. The term should be familiar to you though the meaning might not be so clear--think of a salesman showing off his array of fabulous cleaning products or a game show with a dazzling array of prizes. Like variables, arrays are created by stating the type of the variable being organized into an array and the name of the array. The difference lies in the addition of the square bracket marks [ and ].

You can create arrays for any type of information that can be stored as a variable. For example, the following statement creates an array of string variables:

String[] naughtyChild;

Here are a few more examples:

int[] reindeerWeight;
boolean[] hostileAirTravelNations;

Java is flexible about where the square brackets are placed when an array is being created. You can put them after the variable name instead of after the variable type, as in the following:

String niceChild[];

To make arrays easier for humans to spot in your programs, you probably should stick to one style rather than switching back and forth, though Java allows both styles of usage.

The previous examples create arrays, but they do not store any values in them initially. To do this, you must use the new statement along with the variable type or store values in the array within { and } marks. You also must specify how many different items will be stored in the array. Each item in an array is called an element. The following statement creates an array and sets aside space for the values that it will hold:

int[] elfSeniority = new int[250];

This example creates an array of integers called elfSeniority. The array has 250 elements in it that can be used to store the number of months that each of Santa's elves has been employed at the Pole. If the rumors are true and Santa runs a union shop, this information is extremely important to keep track of.

When you create an array with the new statement, you must specify the number of elements. Each element of the array is given an initial value when it is set up with new; the value depends on the type of the array. All numeric arrays have the value 0, char arrays have the value `\0', and boolean arrays have the value false. A String array and all other objects are created with the initial value of null.

For arrays that are not extremely large, you can set up their initial values at the same time that you create them. The following example creates an array of strings and gives them initial values:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen" };

The information that should be put into elements of the array is put between { and } brackets, and commas separate each element. The number of elements in the array is not specified in the statement because it is set to the number of elements in the comma-separated list. Each element of the array in the list must be of the same type. The preceding example uses a string for each of the reindeer names.

Once the array is created, you cannot make more space and add another variable to the array. Even if you recall the most famous reindeer of all, you couldn't add "Rudolph" as the ninth element of the reindeerNames array. The javac compiler won't let poor Rudolph join in any reindeerNames.

Using Arrays

You use arrays in a program as you would use any variable, except for the element number in between the square brackets next to the array's name. Once you refer to the element number, you can use an array element anywhere that a variable could be used. The following statements all use arrays that have been defined already in this hour's examples:

elfSeniority[193] += 1;
niceChild[94287612] = "Jonathan Bourne";
if ( hostileAirTravelNations[currentNation] == true)
    sendGiftByMail();

An important thing to note about arrays is that the first element of an array is numbered 0 instead of 1. This means that the highest number is one less than you might expect. For example, consider the following statement:

String[] topGifts = new String[10];

This statement creates an array of String variables that are numbered from 0 to 9. If you referred to a topGifts[10] somewhere else in the program, you would get an error message like the following when you run the program:

java.lang.ArrayIndexOutOfBoundsException:
        at SantaGifts.main(SantaGifts.java:4);

Like all of the error messages Java generates, this one's a bit hard to decipher. The key thing to note is the part that mentions an exception because exceptions are another word for errors in Java programs. This exception is an "array out of bounds" error, which means that the array has gone beyond its defined boundaries.

If you want to see what the upper limit of an array is during a program so that you can avoid going beyond the limit, you can use a variable called length that is associated with each array that is created. The length variable is an integer that returns the number of elements that an array can hold. The following example creates an array and then reports its length:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",
    "Comet", "Cupid", "Donner", "Blitzen", "Rudolph" };
System.out.println("There are " + reindeerNames.length + " reindeer.");

In this example, the value of reindeerNames.length is 9, which means that the highest element number you can specify is 8.

Multidimensional Arrays

The arrays you have been introduced to thus far in the hour all have one dimension; one line of numbers ranging from 0 to the largest element number is used to refer to an array. But some types of information require more dimensions to store adequately as arrays. An example would be the (x,y) coordinate system that's a staple of any math class. If you needed to store a list of x and y coordinates that have a point marked on them, you could use a two-dimensional array. One dimension of the array could store the x coordinate, and the other dimension could store the y coordinate.

To create an array that has two dimensions, you must use an additional set of square brackets when creating and using the array. Consider the following:

boolean[][] selectedPoint = new int[50][50];
selectedPoint[4][13] = true;
selectedPoint[7][6] = true;
selectedPoint[11][22] = true;

This example creates an array of Boolean values called selectedPoint. The array has 50 elements in its first dimension and 50 elements in its second dimension, so there are 2,500 individual array elements that can hold values (50 multiplied by 50). When the array is created, each element is given the default value of false. Three elements are then given the value of true: A point at the (x,y) position of (4,13), one at (7,6), and one at (11,22).

Arrays can have as many dimensions as you need, but keep in mind that they take up a lot of memory if they're extremely large. Creating the 50 by 50 selectedPoint array was equivalent to creating 2,500 individual variables.

Workshop: Array of Prizes Indeed

Watch the syndicated game show Wheel of Fortune for any length of time and you'll be surprised at how predictable the contestants are. In the years that this show has been one of the world's most successful television programs, fortune seekers have worked the puzzle-solving process into an exact science. Wheel contestants typically guess the same letters when they are starting out on a puzzle: R, S, T, L, and N. In the final round, when these letters and the vowel E are given to the players right away, they usually choose four other letters: C, D, M, and the vowel O. The reason for this predictablity is that these are the letters that appear most often in English words. The contestants are stifling their desire for spontaneity in order to better their chances to win a trip to Bermuda, cash, and a Yamaha Waverunner.

In case you're unfamiliar with the show, Wheel of Fortune is a game in which three contestants try to guess the letters of a phrase, name, quote, or other memorable item. If they get a letter right and it's a consonant, they win the amount of money they spun on a big wheel. To re-create the experience, play hangman with some of your friends in front of a studio audience, hand out random amounts of money when someone guesses a letter in the secret word or phrase, and give the winner a new Ford Explorer.

Your Java workshop during this hour will test the most-common-letter theory by looking at as many different phrases and expressions as you care to type. An array will be used to count the number of times that each letter appears. When you're done, the program will present each letter and the number of times it appears in the phrases you entered. It also will present some clues about which letters to avoid entirely unless you suspect that a puzzle's answer is the Aztec priest-ruler Quetzalcoatl or the fire god Xiuhtecuhtle.

Open up a new file in your word processor and call it Wheel.java. Enter Listing 9.1 and save the file when you're done.

Listing 9.1. The full source code of Wheel.java.

 1: class Wheel {
 2:    public static void main(String arguments[]) {
 3:        String phrase[] = {
 4:            "A STITCH IN TIME SAVES NINE",
 5:            "DON'T EAT YELLOW SNOW",
 6:            "JUST DO IT",
 7:            "EVERY GOOD BOY DOES FINE",
 8:            "I WANT MY MTV",
 9:            "HOW `BOUT THEM COWBOYS",
10:            "PLAY IT AGAIN, SAM",
11:            "FROSTY THE SNOWMAN",
12:            "ONE MORE FOR THE ROAD",
13:            "HOME FIELD ADVANTAGE",
14:            "VALENTINE'S DAY MASSACRE",
15:            "GROVER CLEVELAND OHIO",
16:            "WONDERFUL WORLD OF DISNEY",
17:            "COAL MINER'S DAUGHTER",
18:            "WILL IT PLAY IN PEORIA"
19:        };
20:        int[] letterCount = new int[26];
21:        for (int count = 0; count < phrase.length; count++) {
22:            String current = phrase[count];
23:            char[] letters = current.toCharArray();
24:            for (int count2 = 0;  count2 < letters.length; count2++) {
25:                char lett = letters[count2];
26:                if ( (lett >= `A') & (lett < `Z') ) {
27:                    letterCount[lett - `A']++;
28:                }
29:            }
30:         }
31:        for (char count = `A'; count <= `Z'; count++) {
32:            System.out.print(count + ": " +
33:                    letterCount[count - `A'] +
34:                    "\t");
35:        }
36:        System.out.println();
37:    }
38: } 


After you compile the file and run it, the output should resemble Listing 9.2.

Listing 9.2. The output of the Wheel program.

 A: 22  B: 3   C: 5   D: 13  E: 28  F: 6   G: 5   H: 8   I: 18  J: 1
 K: 0   L: 13  M: 10  N: 19  O: 27  P: 3   Q: 0   R: 13  S: 15  T: 19
U: 4 V: 7 W: 9 X: 0 Y: 10 Z: 0 


The following things are taking place in the Wheel program:

  • Lines 1 and 2: The Wheel program and the main() block of the program begin.

  • Lines 3-19: Phrases are stored in a String array called phrase. Every phrase between the { on Line 3 and the } on Line 19 will be stored in its own element of the array, beginning with A STITCH IN TIME SAVES NINE in phrase[0].

  • Line 20: An integer array called letterCount is created with 26 elements. This array will be used to store the number of times each letter appears. The order of the elements is from A to Z. letterCount[0] will store the count for letter A, letterCount[1] will store the count for B, and so on up to letterCount[25] for Z.

  • Line 21: A for loop is begun that cycles through the phrases stored in the phrase array. The phrase.length variable is used in the for statement to end the loop after the last phrase is reached.

  • Line 22: A String variable named current is created and set with the value of the current element of the phrase array.

  • Line 23: A character array is created that stores all of the characters in the current phrase.

  • Line 24: A for loop is begun that cycles through the letters of the current phrase. The letters.length variable is used to end the loop after the last letter is reached.

  • Line 25: A character variable called lett is created with the value of the current letter. In addition to their text value, characters have a numeric value. Because elements of an array are numbered, the numeric value of each character will be used to determine its element number.

  • Lines 26-28: An if statement is used to weed out all characters that are not part of the alphabet, such as punctuation and spaces. An element of the letterCount array is increased by 1 depending on the numeric value of the current character, which is stored in lett. The numeric values of the alphabet range from 65 for `A' to 90 for `Z'. Because the letterCount array begins at 0 and ends at 25, `A' (65) is subtracted from lett to determine which array element to increase.

  • Line 29: One pass through the inner for loop ends, and the loop returns to Line 24 to get the next letter in the current phrase, if there is one.

  • Line 30: One pass through the outer for loop ends, and the loop returns to Line 21 to get the next phrase, if there is one.

  • Line 31: A for loop is used to cycle through the alphabet from `A' to `Z'.

  • Lines 32-34: The current letter is displayed followed by a semicolon and the number of times the letter appeared in the phrases stored in the phrase array. The \t inserts a Tab character.

  • Line 35: One pass through the for loop ends, and the loop returns to Line 31 to get the next character in the alphabet, unless `Z' has been reached.

  • Lines 36-38: A blank line is displayed, followed by the end of the program's main() block, and the end of the program.

This workshop project shows how two nested for loops can be used to cycle through a group of phrases one letter at a time. Java attaches a numeric value to each character; this value is easier to use than the character inside arrays. Using the length variable makes it possible for you to add as many phrases as desired within the { and } marks. The letters in each of the new phrases that you add will be analyzed, and you can build up a better idea of what it takes to make a small fortune in 30 minutes on television.

Summary

Arrays make it possible to store complicated types of information in a program and manipulate that information. They're ideal for anything that can be arranged in a list and can be accessed easily using the loop statements that you learned about during Chapter 8, "Repeating an Action with Loops."

The information processing needs of Santa Claus possibly have outgrown arrays. There are more children being manufactured each year, and the gifts they want are increasing in complexity and expense. Tickle Me Elmo alone created a logistical nightmare for him in Christmas 1996. Your programs are likely to use arrays to store information that is unwieldy to work with through variables, even if you're not making any lists or checking them twice.

Q&A

Q Do arrays have to begin with an element 0, or could they range from a higher minimum number to a higher maximum number, such as 65 to 90?

A
No, but it is more efficient to do so because it takes up less memory in the computer to store arrays that begin with 0. You can use arrays of a higher index number simply by referring to the numbers you want to use. For example, if you created a for loop that cycled from array element 65 to element 90, you could disregard any other element numbers. However, there still will be array elements numbered from 0 to 64 taking up space in memory, even if you don't use them for anything.

Q Why are some errors called exceptions?

A
The significance of the term is that a program normally runs without any problems, and the exception signals an exceptional circumstance that must be dealt with. Exceptions are warning messages that are sent from within a Java program.

Q Can the length variable be set to increase or decrease the size of an array after it has been
created?

A
There's no way to modify the size of an array after it has been created; length is strictly used to find out an array's upper boundary.

Quiz

If the brain were an array, you could test its length by answering each of the following questions about arrays.

Questions

1. What types of information are arrays best suited for?

(a) Lists
(b) Pairs of related information
Trivia

2.
What variable can be used to check the upper boundary of an array?

(a) top
(b) length
limit

3.
Who is the famous Aztec priest-ruler?

(a) Quisp
(b) Quetzalcoatl
Quichelorraine

Answers

1. a. Lists that contain nothing but the same type of information--strings, numbers, and so on--are well-suited for storage in arrays.

2.
b.

3.
b. It's also the name of a god of learning and civilization who is depicted as an approaching storm whose winds kick up dust before the rain comes.

Activities

To give yourself an array of experiences to draw from later on, you can expand your knowledge of this hour's topics with the following activities:

  • Create a program that uses a multidimensional array to store student grades. The first dimension should be a number for each student, and the second dimension should be for each student's grades. Display the average of all the grades earned by each student and an overall average for every student.

  • Write a program that stores the first 400 prime numbers in an array.