An array initializer may be specified in a declaration, creating an array and providing some initial values:
ArrayInitializer:
{VariableInitializersopt,opt}VariableInitializers:
VariableInitializer
VariableInitializers,VariableInitializer
The following is repeated from §8.3 to make the presentation here clearer:
VariableInitializer:
Expression
ArrayInitializer
An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".
The length of the constructed array will equal the number of expressions.
Each expression specifies a value for one array component. Each expression must be assignment-compatible (§5.2) with the array's component type, or a compile-time error results.
If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.
A trailing comma may appear after the last expression in an array initializer and is ignored.
class Test {
public static void main(String[] args) {
int ia[][] = { {1, 2}, null };
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
System.out.println(ia[i][j]);
}
}
1 2
before causing a NullPointerException in trying to index the second component of the array ia, which is a null reference.