10.3 One-Dimensional Arrays | 489
(^1) Java inherits the notion that charis a numeric type from C. The Java language specifications say that
arrays must be indexed by intvalues but that values of type short,byte, or charmay also be used because
they are subjected to unary numeric promotion and become intvalues. For clarity, we type cast charval-
ues to intwhen using them as indexes.
The Index-Expression may be as simple as a constant or a variable name or as complex as
a combination of variables, operators, and method calls. Whatever the form of the expres-
sion, it must give an integer value as a result. Index expressions can be of type byte,char,short,
or int.^1 Using an index expression of type longproduces a compile-time error.
The simplest form of index expression is a constant. For example, using our anglearray,
the sequence of assignment statements
angle[0] = 4.93;
angle[1] = –15.2;
angle[2] = 0.5;
angle[3] = 1.67;
fills the array components one at a time (see Figure 10.4).
Each array component—angle[2], for instance—can be treated exactly
the same as any simple variable of typefloat. For example, we can do the fol-
lowing to the individual componentangle[2]:
// Assign it a value
angle[2] = 9.6;
// Read a value into it
angle[2] = Double.parseDouble(inFile.readLine());
// Write its contents
outFile.println(angle[2]);
// Pass it as an argument
y = Math.sqrt(angle[2]);
// Use it in an expression
x = 6.8 * angle[2] + 7.5;
Now let’s look at a more complicated index expression. Suppose we declare a 1,000-el-
ement array of intvalues with the statement
int[] value = new int[1000];
and execute the following statement:
value[counter] = 5;
angle[ 0 ]
angle[ 1 ]
angle[ 2 ]
angle[ 3 ]
angle
4.93
–15.2
0.5
1.67
Figure 10.4 angleArray with Values