Java Reference
In-Depth Information
need to cast it to type int . You no doubt recall from Chapter 2 that arithmetic expressions involving values
of type short and type byte produce a result of type int , so you can use those in an index expression.
You refer to the first element of the primes array 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 is 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 type in this case is an ArrayIndexOutOfBoundsException .
When such an exception is thrown, your program is terminated unless there is some provision in your code
for dealing with it. You look at exceptions in detail in Chapter 7, including how you can deal with exceptions
and prevent termination of your program.
The primes array is an example of what is sometimes referred to as a one-dimensional array , because
each of its elements is referenced using one index — running from 0 to 9 in this case. You see later that
arrays can also 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
As I explained at the beginning of this chapter, an array variable is separate from the array that it references.
Rather like the way an ordinary variable can store different values at different times, you can use an array
variable to store a reference to different arrays at different points in your program. Suppose you have de-
clared and defined the variable primes as before, like this:
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 to use
the array variable primes to refer to a larger array, with 50 elements, say. You could simply write the fol-
lowing:
primes = new int[50]; // Allocate an array of 50 integer elements
Now the primes variable 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 be used to reference only elements of
the new array. This is illustrated in Figure 4-2 .
FIGURE 4-2
 
 
Search WWH ::




Custom Search