Java Reference
In-Depth Information
arr aYs
Now we're going to look at a new concept—something called an
array
. An array is similar to a
normal variable, in that you can use it to hold any type of data. However, it has one important
difference, which you see in this section.
As you have already seen, a normal variable can only hold one piece of data at a time. For example,
you can set
myVariable
to be equal to
25
like so:
myVariable
=
25;
and then go and set it to something else, say
35
:
myVariable
=
35;
However, when you set the variable to
35
, the first value of
25
is lost. The variable
myVariable
now
holds just the number
35
.
The following table illustrates the variable:
variaBle name
value
myVariable
35
The difference between such a normal variable and an array is that an array can hold
more than one
item of data at the same time. For example, you could use an array with the name
myArray
to store
both the numbers
25
and
35
. Each place where a piece of data can be stored in an array is called an
element
.
How do you distinguish between these two pieces of data in an array? You give each piece of data
an
index
value. To refer to that piece of data, you enclose its index value in square brackets after
the name of the array. For example, an array called
myArray
containing the data
25
and
35
could be
illustrated using the following table:
elementname
value
myArray[0]
25
myArray[1]
35
Notice that the index values start at
0
and not
1
. Why is this? Surely
1
makes more sense—after all,
we humans tend to say the first item of data, followed by the second item, and so on. Computers
start from
0
, and think of the first item as the zero item, the second as the first item, and so on.
Confusing, but you'll soon get used to this.
Arrays can be very useful because you can store as many (within the limits of the language, which
specifies a maximum of two to the power of 32 elements) or as few items of data in an array as
you want. Also, you don't have to say up front how many pieces of data you want to store in an
array.