Java Reference
In-Depth Information
As with sums, temps can refer to any size array of doubles. Right now, it
refers to an array of 31 doubles.
Because an array object is instantiated using the new keyword, the
memory is zeroed after it is allocated. Therefore, the initial values of the
elements in the array will be their zero value (these values were found in
Table 4.5). For example, the 31 doubles in the temps array are initially 0.0,
and the 30 ints in the sums array are initially 0.
Accessing Arrays
The elements in an array are accessed by using a reference to the array and an
index, an int value denoting which element in the array you want to access.
The first element in the array is index 0, the second element is index 1, and so on.
For example, the following statements declare an array of 20 ints and place
1 in the first element, 2 in the second element, and 191 in the last element:
int [] sums = new int[20];
sums[0] = 1;
sums[1] = 2;
sums[19] = 191;
It takes 20 statements to assign the 20 ints in sums to a value, so for loops go
hand in hand with arrays, as you might imagine. The following for loop
assigns the values in sums to the sum of the first n + 1 numbers, where n is the
index:
sums[0] = 1;
for(int i = 1; i < 20; i++)
{
sums[i] = sums[i-1] + i;
}
The first element in sums is assigned to 1; the for loop initializes the remain-
ing 19 elements.
The length Attribute
Suppose that the size of the sums array is 20 ints:
int [] sums = int[20];
Search WWH ::




Custom Search