At run time, evaluation of an array creation expression behaves as follows.
First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.
Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then an NegativeArraySizeException
is thrown.
Next, space is allocated for the new array. If there is insufficient space to allocate the array, evaluation of the array creation expression completes abruptly by throwing an OutOfMemoryError
.
Then, if a single DimExpr appears, a single-dimensional array is created of the specified length, and each component of the array is initialized to its standard default value (§4.5.4).
If an array creation expression contains N DimExpr expressions, then it effectively executes a set of nested loops of depth to create the implied arrays of arrays. For example, the declaration:
float[][] matrix = new float[3][3];
float[][] matrix = new float[3][]; for (int d = 0; d < matrix.length; d++) matrix[d] = new float[3];
Age[][][][][] Aquarius = new Age[6][10][8][12][];
Age[][][][][] Aquarius = new Age[6][][][][]; for (int d1 = 0; d1 < Aquarius.length; d1++) { Aquarius[d1] = new Age[8][][][]; for (int d2 = 0; d2 < Aquarius[d1].length; d2++) { Aquarius[d1][d2] = new Age[10][][]; for (int d3 = 0; d3 < Aquarius[d1][d2].length; d3++) { Aquarius[d1][d2][d3] = new Age[12][]; } } }
with d, d1, d2 and d3 replaced by names that are not already locally declared.
Thus, a single new
expression actually creates one array of length 6, 6 arrays of
length 10, arrays of length 8, and arrays of length
12. This example leaves the fifth dimension, which would be arrays containing the
actual array elements (references to Age
objects), initialized only to null references. These arrays can be filled in later by other code, such as:
Age[] Hair = { new Age("quartz"), new Age("topaz") }; Aquarius[1][9][6][9] = Hair;
A multidimensional array need not have arrays of the same length at each level; thus, a triangular matrix may be created by:
float triang[][] = new float[100][]; for (int i = 0; i < triang.length; i++) triang[i] = new float[i+1];
There is, however, no way to get this effect with a single creation expression.