ptg7068951
Using Arrays 109
The information that should be stored in elements of the array is placed
between {and }brackets with commas separating each element. The number
of elements in the array is set to the number of elements in the comma-
separated list. Each element of the array must be of the same type. The
preceding example uses a string to hold each of the reindeer names.
After the array is created, you cannot make room for more elements. Even
if you recall the most famous reindeer of all, you couldn’t add “Rudolph”
as the ninth element of the reindeerNamesarray. The Java compiler won’t
let poor Rudolph join in any reindeerNames.
Using Arrays
You usearrays in a program as you would any variable, except for the ele-
ment number between the square brackets next to the array’s name. You can
use an array element anywhere a variable could be used. The following state-
ments all use arrays that have already been defined in this hour’s examples:
elfSeniority[193] += 1;
niceChild[9428] = “Eli”;
if (hostileAirTravelNations[currentNation] == true) {
sendGiftByMail();
}
The first element of an array is numbered 0 instead of 1. This means that
the highest number is one less than you might expect. Consider the follow-
ing statement:
String[] topGifts = new String[10];
This statement creates an array of string variables numbered from 0 to 9. If
you referred to topGifts[10]somewhere else in the program, you would
get an error message referring to an ArrayIndexOutOfBoundsException.
Exceptionsare another word for errors in Java programs. This exception is an
“array index out of bounds”error, which means that a program tried to use
an array element that doesn’t exist within its defined boundaries. You learn
more about exceptions during Hour 18, “Handling Errors in a Program.”
If you want to check the upper limit of an array so you can avoid going
beyond that limit, a variable called lengthis associated with each array
that is created.The lengthvariable is an integer that contains the number
of elements an array holds. The following example creates an array and
then reports its length: