Java Reference
In-Depth Information
System . out . println ( prime . length ) ;
We cannot change the size of arrays once initialized. For example, trying to force
the length of array
array
by setting
array.length=23;
will generate the fol-
lowing compiler message error:
cannot assign a value to final variable
length
.
4.2.4 Index range of arrays and out-of-range exceptions
Arrays created with the syntax
array=new TYPE[Expression]
have a fixed
length determined at the instruction call time by evaluating the expression
Expression
to its integer value, say
l
(with
l=array.length
). The elements
of that array are accessed by using an index ranging from 0 (lower bound) to
l
1 (upper bound):
array[0]
...
array[l-1]
A frequent programming error is to try to access an element that does not
belong to the array by giving an inappropriate index falling out of the range
[0
,l
−
1]. The following program demonstrates that Java raises an exception if
we try to use out-of-range indices:
−
Program 4.2
Arrays and index out of bounds exception
class
ArrayBound
{
public static void
main ( String [ ]
args )
{
int
[]v=
{
0,1,2,3,4,5,6,7,8
}
;
long
l=v. length ;
System . out . println (
"Size of array v:"
+l ) ;
System . out . println (v [ 4 ] ) ;
System . out . println (v [1 2]) ;
}
}
Running the above program yields the following console output:
Size of array v:9
4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
at ArrayBound.main(ArrayBound.java:8)
That is, index out of bounds cannot be checked by the compiler and may
happen at
any
time when executing the program.
A
subarray
is a
consecutive portion
of an array: For example,
array[3..7];
.
Java does not provide language support for manipulating subarrays so that one
has to explicitly keep track of the lower and upper bounds of subarrays.
Search WWH ::
Custom Search