Java Reference
In-Depth Information
Declaring array variables
The LogAnalyzer class contains a field that is of an array type:
private int[] hourCounts;
The distinctive feature of an array variable's declaration is a pair of square brackets as part of
the type name: int[] . This indicates that the hourCounts variable is of type integer array.
We say that int is the base type of this particular array, which means that the array object will
store values of type int . It is important to distinguish between an array-variable declaration
and a similar-looking simple-variable declaration:
int hour; // A single int variable.
int[] hourCounts; // An int-array variable.
Here, the variable hour is able to store a single integer value, whereas hourCounts will be
used to refer to an array object once that object has been created. An array-variable declaration
does not itself create the array object. That takes place in a separate stage using the new opera-
tor, as with other objects.
It is worth looking at the unusual syntax again for a moment. The declaration int[] would in
more conventional syntax appear, maybe, as Array<int> . That it does not has historical rather
than logical reasons. You should still get used to reading it in the same way: as “array of int.”
Exercise 4.62 Write a declaration for an array variable people that could be used to refer
to an array of Person objects.
Exercise 4.63 Write a declaration for an array variable vacant that could be used to refer
to an array of boolean values.
Exercise 4.64 Read through the LogAnalyzer class and identify all the places where the hour-
Counts variable is used. At this stage, do not worry about what all the uses mean, as they will be
explained in the following sections. Note how often a pair of square brackets is used with the variable.
Exercise 4.65 What is wrong with the following array declarations? Correct them.
[]int counts;
boolean[5000] occupied;
Creating array objects
The next thing to look at is how an array variable is associated with an array object.
The constructor of the LogAnalyzer class includes a statement to create an int array object:
hourCounts = new int[24];
Once again, notice how different the syntax is from that of normal object creation. For instance,
there are no round brackets for a constructor's parameters, because an array object does not
have a constructor. This statement creates an array object that is able to store 24 separate integer
values and makes the hourCounts array variable refer to that object. The value of 24 is the size
of the array, and not a constructor parameter. Figure 4.7 illustrates the result of this assignment.
Search WWH ::

Custom Search