Java Reference
In-Depth Information
The expression height[8] refers to a single integer stored at a particular memory
location. It can be used wherever an integer variable can be used. Therefore you can
assign a value to it, use it in calculations, print its value, and so on. Furthermore,
because array indexes are integers, you can use integer expressions to specify the index
used to access an array. These concepts are demonstrated in the following lines of code:
height[2] = 72;
height[count] = feet * 12;
average = (height[0] + height[1] + height[2]) / 3;
System.out.println ("The middle value is " + height[MAX/2]);
pick = height[rand.nextInt(11)];
Arrays are stored contiguously in memory, meaning that the elements are stored
one right after the other in memory just as we picture them conceptually. This
makes an array extremely efficient in terms of accessing any particular element by
its index. Internally, to determine the address of any particular element, the index
is multiplied by the size of each element, and added to the memory address of the
starting point of the array. That's why array indexes begin at zero instead of one—
to make that computation as easy as possible. So from an efficiency point of view,
it's as easy to access the 500th element in the array as it is to access the first element.
SELF-REVIEW QUESTIONS (see answers in Appendix N)
SR 8.1
What is an array?
SR 8.2
How is each element of an array referenced?
SR 8.3
Based on the array shown in Figure 8.1, what are each of the
following?
a. height[1]
b. height[2] + height[5]
c. height[2 + 5]
d. the value stored at index 8
e. the fourth value
f. height.length
8.2 Declaring and Using Arrays
In Java, arrays are objects. To create an array, the reference to the array must be
declared. The array can then be instantiated using the new operator, which allo-
cates memory space to store values. The following code represents the declaration
for the array shown in Figure 8.1:
int [] height = new int [11];
 
Search WWH ::




Custom Search