Java Reference
In-Depth Information
Figure 4.7
An array of
24 integers
KRXU&RXQWV
LQW>@
The general form of an array object's construction is
new type [ integer-expression ]
The choice of type specifies what type of items are to be stored in the array. The integer expres-
sion specifies the size of the array—that is, the fixed number of items that can be stored in it.
When an array object is assigned to an array variable, the type of the array object must match
the declared type of the variable. The assignment to hourCounts is allowed because the array
object is an integer array, and hourCounts is an integer-array variable. The following declares
a string-array variable and makes it refer to an array that has a capacity of 10 strings:
String[] names = new String[10];
It is important to note that the creation of the array assigned to names does not actually create
10 strings. Rather, it creates a fixed-size collection that is able to have 10 strings stored within
it. Those strings will probably be created in another part of the class to which names belongs.
Immediately following its creation, an array object can be thought of as empty. If it is an array
for objects, then the array will contain null values for all elements. If it is an int array, then
all elements will be set to zero. In the next section we shall look at the way in which items are
stored into (and retrieved from) arrays.
Exercise 4.66 Given the following variable declarations,
double[] readings;
String[] urls;
TicketMachine[] machines;
write assignments that accomplish the following tasks: (a) Make the readings variable refer
to an array that is able to hold sixty double values; (b) Make the urls variable refer to an
array that is able to hold ninety String objects; (c) Make the machines variable refer to an
array that is able to hold five TicketMachine objects.
Exercise 4.67 How many String objects are created by the following declaration?
String[] labels = new String[20];
 
Search WWH ::




Custom Search