Java Reference
In-Depth Information
6
Arrays
Memory is necessary for all the operations of reason.
BLAISE PASCAL,
Pensées
Introduction
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
An
array
or a list of strings. In this chapter we
introduce you to the basics of defining and using arrays in Java.
double
Prerequisites
Section 6.1 requires 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 Sec-
tion 5.4 on packages and
is not required.
javadoc
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
, 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 per-
fect solution. An
. We could use five individual variables of type
int
int
behaves like a list of variables with a uniform naming mecha-
nism that can be declared in a single line of simple code. For example, the names for
the five individual variables we need might be
array
array
,
,
,
score[0]
score[1]
score[2]
, is the
name of the array. The part that can change is the integer in the square brackets
, and
. The part that does not change, in this case
score[3]
score[4]
score
.
[]
Search WWH ::




Custom Search