Java Reference
In-Depth Information
The println method invocation shows how array components are ac-
cessed. It encloses the index of the desired element within square
brackets following the array name.
You can probably tell from reading the code that array objects have
a length field that says how many elements the array contains. The
bounds of an array are integers between 0 and length-1 , inclusive. It is
a common programming error, especially when looping through array
elements, to try to access elements that are outside the bounds of the
array. To catch this sort of error, all array accesses are bounds checked,
to ensure that the index is in bounds. If you try to use an index that is
out of bounds, the runtime system reports this by throwing an excep-
tion in your programan ArrayIndexOutOfBoundsException . You'll learn about
exceptions a bit later in this chapter.
An array with length zero is an empty array. Methods that take arrays
as arguments may require that the array they receive is non-empty and
so will need to check the length. However, before you can check the
length of an array you need to ensure that the array reference is not
null . If either of these checks fail, the method may report the problem
by throwing an IllegalArgumentException . For example, here is a method
that averages the values in an integer array:
static double average(int[] values) {
if (values == null)
throw new IllegalArgumentException();
else
if (values.length == 0)
throw new IllegalArgumentException();
else {
double sum = 0.0;
for (int i = 0; i < values.length; i++)
sum += values[i];
return sum / values.length;
}
 
Search WWH ::




Custom Search