Java Reference
In-Depth Information
6
Memory is necessary for all the operations of reason.
BLAISE PASCAL, Pensées
Introduction
An array is a data structure used to process a collection of data that is all of the same
type, such as a list of numbers of type double or a list of strings. In this chapter, we
introduce you to the basics of defining and using arrays in Java.
Prerequisites
Section 6.1 requires understanding of only Chapters 1 through 3 and Section 4.1 of
Chapter 4. Indeed, much less than all of Section 4.1 is needed. All you really need from
Section 4.1 is to have some idea of what an object is and what an instance variable is.
The remaining sections require Chapters 1 through 5 with the exception that an
understanding of Section 5.4 on packages and javadoc is not required.
6.1
Introduction to Arrays
It is a capital mistake to theorize before one has data.
SIR ARTHUR CONAN DOYLE, Scandal in Bohemia (SHERLOCK HOLMES)
Suppose we wish to write a program that reads in five test scores and performs some
manipulations on these scores. For instance, the program might compute the highest
test score and then output the amount by which each score falls short of the highest.
The highest score is not known until all five scores are read in. Hence, all five scores
must be retained in storage so that after the highest score is computed, each score
can be compared to it. To retain the five scores, we will need something equivalent
to five variables of type int . We could use five individual variables of type int , but
keeping track of five variables is hard, and we may later want to change our program
to handle 100 scores; certainly, keeping track of 100 variables is impractical. An array
is the perfect solution. An array behaves like a list of variables with a uniform naming
mechanism that can be declared in a single line of simple code. For example, the names
for the five individual variables we need might be score[0] , score[1] , score[2] ,
score[3] , and score[4] . The part that does not change—in this case, score —is the
name of the array. The part that can change is the integer in the square brackets [] .
array
 
 
Search WWH ::




Custom Search