Java Reference
In-Depth Information
This statement creates an array named finalGrade,of type int,and allo -
cates space for storing 14 elements. The first element is located at index
number 0,and the last one at index number 13.
Programmers note:
An array that allocates space for 14 elements does not have an ele-
ment at index 14. The largest index in this case is 13. In programming
arrays you must be careful not to attempt to access an element that
does not exist.
You can now store information in the array finalGrade,as follows:
finalGrade[0] = 78;
finalGrade[1] = 88;
and so on. The last element in the array is accessed as follows:
finalGrade[13] = 55;
Java recognizes a special syntax in arrays in which the new operator is
implicit. This allows declaring,creating,and initializing an array in a sin-
gle statement; for example:
int nums[] = {0, 1, 1, 2, 3, 5, 8, 13, 21};
The resulting array contains nine elements. The first one is located at
nums[0] and the last one at nums[8].
Incidentally...
In contrast with its predecessor languages,C and C++,Java performs
considerable checking on arrays. If you try to access a non-allocated
array Java throws a NullPointerException. If you attempt to access an
array element out of the array bounds,Java throws an ArrayIndex -
OutOfBoundsException. Exceptions are discussed in Chapter 19.
A String array can be created and initialized as follows:
String[] studentNames = {“Jim”, “Jane”, “Harry”, “Lucy”};
The array brackets
For a beginning programmer it is confusing that in array declarations the
brackets can be attached either to the array type or to the name. For exam-
ple:
Search WWH ::




Custom Search