The {...}
construct here is called an array initializer in Java. It is a special shorthand that is only available in certain grammatical constructs:
An array initializer may be specified in a declaration, or as part of an array creation expression, creating an array and providing some initial values. [...] An array initializer is written as a comma-separated list of expressions, enclosed by braces "{"
and "}"
.
As specified, you can only use this shorthand either in the declaration or in an array creation expression.
int[] nums = { 1, 2, 3 }; // declaration
nums = new int[] { 4, 5, 6 }; // array creation
This is why the following does not compile:
// DOES NOT COMPILE!!!
nums = { 1, 2, 3 };
// neither declaration nor array creation,
// array initializer syntax not available
Also note that:
- A trailing comma may appear; it will be ignored
- You can nest array initializer if the element type you're initializing is itself an array
Here's an example:
int[][] triangle = {
{ 1, },
{ 2, 3, },
{ 4, 5, 6, },
};
for (int[] row : triangle) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
The above prints:
1
2 3
4 5 6
See also