Java Reference
In-Depth Information
VariableInitializer:
Expression
ArrayInitializer
An array initializer is written as a comma-separated list of expressions, enclosed by braces
{
and
}
.
A trailing comma may appear after the last expression in an array initializer and is ignored.
type, or a compile-time error occurs.
It is a compile-time error if the component type of the array being initialized is not reifiable
The length of the array to be constructed is equal to the number of variable initializers im-
mediately enclosed by the braces of the array initializer. Space is allocated for a new array
of that length. If there is insufficient space to allocate the array, evaluation of the array ini-
tializer completes abruptly by throwing an
OutOfMemoryError
. Otherwise, a one-dimensional
array is created of the specified length, and each component of the array is initialized to its
The variable initializers immediately enclosed by the braces of the array initializer are then
executed from left to right in the textual order they occur in the source code. The
n
'th vari-
able initializer specifies the value of the
n
-1'th array component. If execution of a variable
initializer completes abruptly, then execution of the array initializer completes abruptly for
the same reason. If all the variable initializer expressions complete normally, the array ini-
tializer completes normally, with the value of the newly initialized array.
If the component type is an array type, then the variable initializer specifying a component
may itself be an array initializer; that is, array initializers may be nested. In this case, exe-
cution of the nested array initializer constructs and initializes an array object by recursive
application of the algorithm above, and assigns it to the component.
Example 10.6-1. Array Initializers
class Test {
public static void main(String[] args) {
int ia[][] = { {1, 2}, null };
for (int[] ea : ia) {
for (int e: ea) {