Java Reference
In-Depth Information
Consider the following declaration:
double
[] num =
double
[10];
int
i;
The element
num[i]
is valid, that is,
i
is a valid index if
i = 0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,or
9
.
The index—say,
index
—of an array is in bounds if
index >= 0
and
index
<= arraySize - 1
.Ifeither
index < 0
or
index > arraySize - 1
,thenwesay
that the index is out of bounds.
In Java, if an array index goes out of bounds during program execution, it throws an
ArrayIndexOutOfBoundsException
exception. If the program does not handle this
exception, the program terminates with an appropriate error message.
A loop such as the following can set the index out of bounds:
for
(i = 0; i <= 10; i++)
list[i] = 0;
Here, we assume that
list
is an array of
10
elements. When
i
becomes
10
, the loop test
condition
i <= 10
evaluates to
true
, the body of the loop executes, and the program tries
to access
list[10]
, which does not exist.
BASE ADDRESS OF AN ARRAY
The base address of an array is the address (memory location) of the first array element.
For example, if
list
is a one-dimensional array, then the base address of
list
is the
address of the element
list[0]
. The value of the variable
list
is the base address of
the array—the address of
list[0]
. It follows that when you pass an array as a parameter,
the base address of the actual array is passed to the formal parameter.
Just like other data types, you can declare arrays as formal parameters to methods. A
general syntax to declare an array as a formal parameter is:
dataType[] arrayName
For example, consider the following method:
public static void
arraysAsFormalParameter(
int
[] listA,
double
[] listB,
int
num)
{
//...
}
This method has three formal parameters. The formal parameters
listA
and
listB
are
arrays, and
num
is of type
int
.
Search WWH ::
Custom Search