Java Reference
In-Depth Information
type int that is equal to or greater than zero. Obviously a for loop is going to be very useful for processing
array elements — which is one reason why you had to wait until now to hear about arrays.
Array Variables
An array variable and the array it refers to are separate entities. The memory that is allocated for an array
variable stores a reference to an array object, not the array itself. The array object itself is a distinct entity
that is elsewhere in memory. All variables that refer to objects store references that record the memory loc-
ations of the objects they refer to.
You are not obliged to create an array when you declare an array variable. You can first create the array
variable and later use it to store a reference to a particular array.
You could declare the integer array variable primes with the following statement:
int[] primes; // Declare an integer array variable
The variable primes is now a placeholder for an integer array that you have yet to define. No memory
has been allocated to hold an array itself at this point. The primes variable is simply a location in memory
that can store a reference to an array. You see in a moment that to create the array itself you must specify its
type and how many elements it is to contain. The square brackets following the type in the previous state-
ment indicates that the variable is for referencing an array of int values, and not for storing a single value
of type int . The type of the array variable is 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 array of values of type int .
Defining an Array
After you have declared an array variable, you can define an array that it references:
primes = new int[10]; // Define an array of 10 integers
This statement creates an array that stores 10 values of type int and stores 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
Figure 4-1 .
FIGURE 4-1
 
 
Search WWH ::




Custom Search