Java Reference
In-Depth Information
To save space, we also draw an array, as shown in Figures 9-2(a) and 9-2(b).
[0] [1] [2] [3] [4]
num[0] num[1] num[2] num[3] num[4]
num
num
0
0
0
0
0
0
0
0
0
0
(
a
)
(b)
FIGURE 9-2 Array num
Alternate Ways to Declare an Array
Java allows you to declare arrays as follows:
int list[];
//Line 1
Here, the operator [] appears after the identifier list , not after the data type int .
You should be careful when declaring arrays as in Line 1. Consider the following statements:
int alpha[], beta;
//Line 2
int [] gamma, delta;
//Line 3
The statement in Line 2 declares the variables alpha and beta . Similarly, the statement
in Line 3 declares the variables gamma and delta . However, the statement in Line 2
declares only alpha to be an array reference variable, while the variable beta is an int
variable. On the other hand, the statement in Line 3 declares both gamma and delta to
be array reference variables.
Traditionally, Java programmers declare arrays as shown in Line 3. We recommend that
you do the same.
9
Accessing Array Elements
The general form (syntax) used to access an array element is:
arrayName[indexExp]
where indexExp , called the index, is an expression whose value is a nonnegative integer
less than the size of the array. The index value specifies the position of the element in the
array. In Java, the array index starts at 0 .
In Java, [] is an operator called the array subscripting operator.
 
 
Search WWH ::




Custom Search