Java Reference
In-Depth Information
data[1] is the second element
data[2] is the third element
and so on. This convention can be a source of grief for the newcomer, so you should
pay close attention to the index values. In particular, the last element in the array has
an index one less than the array length. For example, data refers to an array with
length 10. The last element is data[9] .
If you try to access an element that does not exist, then an exception is thrown. For
example, the statement
data[10] = 29.95; // ERROR
is a bounds error.
Index values of an array range from 0 to length - 1 . Accessing a nonexistent
element results in a bounds error.
To avoid bounds errors, you will want to know how many elements are in an array.
The length field returns the number of elements: data.length is the length
of the data array. Note that there are no parentheses following length Ȍit is an
instance variable of the array object, not a method. However, you cannot assign a new
value to this instance variable. In other words, length is a final public
instance variable. This is quite an anomaly. Normally, Java programmers use a
method to inquire about the properties of an object. You just have to remember to
omit the parentheses in this case.
Use the length field to find the number of elements in an array.
The following code ensures that you only access the array when the index variable i
is within the legal bounds:
if (0 <= i && i < data.length) data[i] = value;
Search WWH ::




Custom Search