10.5 A r r a y s o f Objects | 499
{
groceryItems[index] = anItem;
index++;
anItem = inFile.readLine();
};
System.out.println(index + " grocery items were read and stored.");
Look carefully at Figures 10.9 and 10.10. In Figure 10.9, every slot in the array is filled with
grocery items. In Figure 10.10,indexitems have been read in and stored. If indexis equal to
10, then the two figures are the same. To process the items in Figure 10.10, you use a loop that
goes from 0 through index– 1.
You first saw a reference to an array of strings in Chapter 2. In the class PrintName, the
following statement appears:
public static voidmain(String[] args) throwsIOException
The parameter for the methodmainis an array of strings,
calledargsby convention. You can run Java applications
in ways that allow you to pass string arguments tomain.
Although we do not use this feature in our applications,
we still have to list the parameter on the heading.
In the figures throughout this chapter, we have drawn
array variables with an arrow to the object structure to
which they refer. An array type is a reference type. When
we declare an array variable with the namegroceryItems,
one location in memory is assigned to that name. When
we instantiate the array, the address of the place in mem-
ory where the actual structure begins is stored into the
locationgroceryItems. This address is called thebase ad-
dressof the array.
If the component type is an atomic type, the values
are actually stored in the memory locations beginning
at the base address. If the component type is a reference
type, a reference to the first component is stored at the base address. We have used
the arrow in our drawings as a visual reminder that the reference variable con-
tains the address indicating where the actual object can be found.
Clearly, strings and arrays are related. You can visualize a string as an array
of characters. Conversely, you can visualize an array as a string of values. Because
of this similarity, the Stringclass has methods that transform a string into an ar-
ray of charand an array of char(char[]) into a string. The method toCharArrayin
the class Stringconverts a string value into a char[]. The method valueOftakes a char[]and
converts it into a string.
groceryItems[0]
groceryItems[1]
groceryItems[ 2 ]
groceryItems[ 3 ]
groceryItems[ 9 ]
groceryItems
"cat food"
"rice"
"chicken"
"bib lettuce"
groceryItems[index– 1 ] "carrots"
Figure 10.10 Partially Filled Array
Base address The memory
address of the first element of
an array