Java Reference
In-Depth Information
An array is a named set of variables of the same type. Each variable in the array is called an
array
element
. To reference a particular element in an array you use the array name combined with an integer
value of type
int
, called an
index
. The index for an array element is the offset of that particular
element from the beginning of the array. The first element will have an index of 0, the second will have
an index of 1, the third an index of 2, and so on. The index value does not need to be an integer literal.
It can be any expression that results in a value of type
int
equal to or greater than zero. Obviously a
for
loop control variable is going to be very useful for processing array elements - which is why you
had to wait until now to hear about arrays.
Array Variables
You are not obliged to create the array itself when you declare the array variable. The array variable is
distinct from the array itself. You could declare the integer array variable
primes
with the statement:
int[] primes; // Declare an integer array variable
The variable
primes
is now a place holder for an integer array that you have yet to define. No memory
is allocated to hold the array itself at this point. We will see in a moment that to create the array itself
we must specify its type and how many elements it is to contain. The square brackets following the type
in the previous statement indicates that the variable is for referencing an array of
int
values, and not
for storing a single value of type
int
.
You may come across an alternative notation for declaring an array variable:
int primes[]; // Declare an integer array variable
Here the square brackets appear after the variable name, rather than after the type name. This is exactly
equivalent to the previous statement so you can use either notation. Many programmers prefer the
original notation, as
int[]
tends to indicate more clearly that the type is an
int
array.
Defining an Array
Once you have declared an array variable, you can define an array that it will reference:
primes = new int[10]; // Define an array of 10 integers
This statement creates an array that will store 10 values of type
int
, and records a
reference
to the
array in the variable
primes
. The reference is simply where the array is in memory. You could also
declare the array variable and define the array of type
int
to hold 10 prime numbers with a single
statement, as shown in the following illustration: