Java Reference
In-Depth Information
Reassigning an Array Variable
After executing the statement shown in the diagram, 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 specified when the array
variable was declared. The variable primes , for example, can only reference arrays of type int . We
have used an int array in the illustration, but everything applies equally well to long or double or to
any of the basic types. More than that, you can create arrays of any other type of object, including the
classes that you will be defining yourself in Chapter 5.
Initializing Arrays
You can initialize an array with your own values when you declare it, and at the same time determine
how many elements it will have. Following the declaration of the array variable, simply add an equal
sign followed by the list of element values enclosed between braces. For example, if you write:
int[] primes = {2, 3, 5, 7, 11, 13, 17}; // An array of 7 elements
the array is created 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. If you specify initializing values for an array, you must
include values for all the elements. If you only want to set some of the array elements to values
explicitly, you should use an assignment statement for each element. For example:
int[] primes = new int[100];
primes[0] = 2;
primes[1] = 3;
The first statement declares and defines an integer array of 100 elements, all of which will be initialized
to zero. The two assignment statements then set values for the first two array elements.
Search WWH ::




Custom Search