ptg7068951
108 HOUR 9:Storing Information with Arrays
Creating Arrays
Arrays are variables grouped together under a common name. The term
array should be familiar to you—think of a salesperson showing off her
array of products or a game show with a dazzling array of prizes. Like
variables, arrays are created by stating the type of variable being organized
into the array and the name of the array. Apair of square brackets ([])
follow the type to distinguish arrays from variables.
You can create arrays for any type of information that can be stored as a
variable. For example, the following statement creates an array of string
variables:
String[] naughtyChild;
Here are two more examples:
int[] reindeerWeight;
boolean[] hostileAirTravelNations;
The previous examples create arrays, but they do not store any values in
them. To do this, you can use the newkeyword along with the variable
type or store values in the array within {and }marks. When using new,
you must specify how many different items are stored in the array. Each
item in an array is called an element. The following statement creates an
array and sets aside space for the values that it holds:
int[] elfSeniority = new int[250];
This example creates an array of integers called elfSeniority. The array
has 250 elements that can store the months that each of Santa’s elves has
been employed at the Pole. If Santa runs a union shop, this information is
extremely important to track.
When you create an array with the newstatement, you must specify the
number of elements. Each element of the array is given aninitial value that
depends on the type of the array. All numeric arrays have the initial value
0, chararrays equal ‘\0’, and booleanarrays have the value false. A
Stringarray and all other objects are created with the initial value of null.
For arrays that are not extremely large, you can set up their initial values at
the same time that you create them. The following example creates an
array of strings and gives them initial values:
String[] reindeerNames = { “Dasher”, “Dancer”, “Prancer”, “Vixen”,
“Comet”, “Cupid”, “Donder”, “Blitzen”};
NOTE
Java is flexible about where the
square brackets are placed
when an array is being created.
Yo u c a n p u t t h e m a f t e r t h e v a r i-
able name instead of the vari-
able type,as in the following:
String niceChild[];
To m a ke a r r ay s e a s i e r f o r
humans to spot in your pro-
grams,you should stick to one
style rather than switching back
and forth. Examples in this
book always place the brackets
after the variable or class type.