Java Reference
In-Depth Information
An
array
is a flexible structure for storing a sequence of values that are all of the
same type.
Array
An indexed structure that holds multiple values of the same type.
The values stored in an array are called
elements.
The individual elements are
accessed using an integer
index.
Index
An integer indicating the position of a particular value in a data structure.
As an analogy, consider post office boxes. The boxes are indexed with numbers, so
you can refer to an individual box by using a description like “P.O. Box 884.” You
already have experience using an index to indicate positions within a
String
; recall
the methods
charAt
and
substring
. Like
String
indexes, array indexes start with 0.
This is a convention known as
zero-based indexing.
Zero-Based Indexing
A numbering scheme used throughout Java in which a sequence of values
is indexed starting with 0 (element 0, element 1, element 2, and so on).
It might seem more natural to start indexes with 1 instead of 0, but Sun decided
that Java would use the same indexing scheme that is used in C and C++.
Suppose you want to store some different temperature readings. You could keep them
in a series of variables:
double temperature1;
double temperature2;
double temperature3;
This isn't a bad solution if you have just 3 temperatures, but suppose you need to
store 3000 temperatures. Then you would want a more flexible way to store the values.
You can instead store the temperatures in an array.
When you use an array, you first need to declare a variable for it, so you have to
know what type to use. The type will depend on the type of elements you want to
have in your array. To indicate that you are creating an array, follow the type name
with a set of square brackets:
[]
. If you are storing temperature values, you want a
Search WWH ::
Custom Search