Java Reference
In-Depth Information
After an array is created, an indexed variable can be used in the same way as a regular
variable. For example, the following code adds the values in
myList[0]
and
myList[1]
to
myList[2]
.
myList[
2
] = myList[
0
] + myList[
1
];
The following loop assigns
0
to
myList[0]
,
1
to
myList[1]
, . . . , and
9
to
myList[9]
:
for
(
int
i =
0
; i < myList.length; i++) {
myList[i] = i;
}
6.2.5 Array Initializers
Java has a shorthand notation, known as the
array initializer
, which combines the declaration,
creation, and initialization of an array in one statement using the following syntax:
array initializer
elementType[] arrayRefVar = {value0, value1, ..., valuek};
For example, the statement
double
[] myList = {
1.9
,
2.9
,
3.4
,
3.5
};
declares, creates, and initializes the array
myList
with four elements, which is equivalent to
the following statements:
double
[] myList =
new double
[
4
];
myList[
0
] =
1.9
;
myList[
1
] =
2.9
;
myList[
2
] =
3.4
;
myList[
3
] =
3.5
;
Caution
The
new
operator is not used in the array-initializer syntax. Using an array initializer, you
have to declare, create, and initialize the array all in one statement. Splitting it would
cause a syntax error. Thus, the next statement is wrong:
double
[] myList;
myList = {
1.9
,
2.9
,
3.4
,
3.5
};
6.2.6 Processing Arrays
When processing array elements, you will often use a
for
loop—for two reasons:
All of the elements in an array are of the same type. They are evenly processed in the
same fashion repeatedly using a loop.
■
Since the size of the array is known, it is natural to use a
for
loop.
■
Assume the array is created as follows:
double
[] myList =
new double
[
10
];
The following are some examples of processing arrays.
1.
Initializing arrays with input values:
The following loop initializes the array
myList
with user input values.
java.util.Scanner input =
new
java.util.Scanner(System.in);
System.out.print(
"Enter "
+ myList.length +
" values: "
);
for
(
int
i =
0
; i < myList.length; i++)
myList[i] = input.nextDouble();