Java Reference
In-Depth Information
The first element of the primes array that we declared previously is referred to as primes[0] , and
you reference the fifth element in the array as primes[4] . The maximum index value for an array is
one less than the number of elements in the array. Java checks that the index values you use are valid. If
you use an index value that is less than 0, or greater than the index value for the last element in the
array, an exception will be thrown - throwing an exception is just the way errors at execution time are
signaled and there are different types of exceptions for signaling various kinds of errors. The exception
in this case is called an IndexOutOfBoundsException . When such an exception is thrown, your
program will normally be terminated. We will be looking in detail at exceptions in Chapter 7, including
how you can deal with exceptions and prevent termination of your program.
The array, primes , is what is sometimes referred to as a one-dimensional array , since each of its
elements is referenced using one index - running from 0 to 9 in this case. We will see later that arrays
can have two or more dimensions, the number of dimensions being the same as the number of indexes
required to access an element of the array.
Reusing Array Variables
The array variable is separate from the array itself. Rather like the way an ordinary variable can refer to
different values at different times, you can use an array variable to reference different arrays at different
points in your program. Suppose you have declared and defined the variable primes as before:
int[] primes = new int[10]; // Allocate an array of 10 integer elements
This produces an array of 10 elements of type int . Perhaps a bit later in your program you want the
array variable primes to refer to a larger array, with 50 elements say. You would simply write:
primes = new int[50]; // Allocate an array of 50 integer elements
Now the variable primes refers to a new array of values of type int that is entirely separate from the
original. When this statement is executed, the previous array of 10 elements is discarded, along with all
the data values you may have stored in it. The variable primes can now only be used to reference
elements of the new array. This is illustrated in the next diagram.
Search WWH ::




Custom Search