When an array is declared, the
array's dimensions must be specified using a pair of matching braces (i.e.,
[]
).
Java provides a lot of lexibility on how these braces may be placed. They may be placed to the right of the array type or to the right of the array identifier.
Zero or more spaces may be placed around each brace. Each of the following array declarations are equivalent:
Once an array is declared, it must be created. This can be done using an array initializer or using the
new
operator followed by an array dimension expression. Array initializers are used as follows:
int[] i = {1, 2, 3, 4, 5};
The above declares, creates, and initializes an array of five int values. Arrays of arrays may be specified by nesting array initializers.
int[][] i = {{1,2,3}, {4,5,6}, {7,8,9}};
Array initializers work well for small arrays but are impractical for arrays that contain more than a few elements.
To create larger arrays, use the
new
operator followed by the array type and the array size within braces.
String[] s = new String[100];
The above statement declares and initializes an array of 100
String
objects. You can also specify multidimensional arrays using this notation:
String[][] s = new String[200][50];
The above notation is also equivalent to the following:
When an array is created, its elements are automatically initialized as described in the Module "Java Language Fundamentals."