Java Reference
In-Depth Information
After executing the statement shown in Figure 4-2 , the array variable primes now points to a new integer
array of 50 elements with index values running from 0 to 49. Although you can change the array that an
array variable references, you can't alter the type of value that an element stores. All the arrays referenced
by a given variable must correspond to the original type that you specified when you declared the array vari-
able. The variable primes , for example, can only reference arrays of type int[] . You have used an array of
elements of type int in the illustration, but the same thing applies equally well when you are working with
arrays of elements of type long or double or of any other type. Of course, you are not restricted to working
with arrays of elements of primitive types. You can create arrays of elements to store references to any type
of object, including objects of the classes that you define yourself in Chapter 5.
Initializing Arrays
You can initialize the elements in an array with your own values when you declare it, and at the same time
determine how many elements it has. To do this, you simply add an equal sign followed by the list of ele-
ment values enclosed between braces following the specification of the array variable. For example, you can
define and initialize an array with the following statement:
int[] primes = {2, 3, 5, 7, 11, 13, 17}; // An array of 7 elements
This creates the primes array with sufficient elements to store all of the initializing values that appear
between the braces — seven in this case. The array size is determined by the number of initial values so no
other information is necessary to define the array. The values are assigned to the array elements in sequence,
so in this example primes[0] has the initial value 2, primes[1] has the initial value 3, primes[2] has the
initial value 5, and so on through the rest of the elements in the array.
If you want to set only some of the array elements to specific values explicitly, you can create the array
with the number of elements you want and then use an assignment statement for each element for which you
supply a value. For example:
int[] primes = new int[100];
primes[0] = 2;
primes[1] = 3;
Search WWH ::




Custom Search