How are simple and multidimensional Java arrays declared?
Like other Java fields and variables, array-valued fields and variables must be declared before they can be assigned or referenced. These declarations will look familiar to those who have some background in C-related languages, but there are some important differences between Java and C array declarations.
An array-valued field or variable is declared by stating the element type, followed by empty brackets to indicate that we are declaring an array of that type. This is then followed by the name of the field or variable. For example, to declare the variable durations
as a reference to an array of int
elements, we write
int[] durations;
Actually, because of the C lineage of Java, an alternative syntax is also supported:
int durations[];
The two declarations above are equivalent; the first is generally preferred in Java code.
A multidimensional array declaration is simply an extension of the above. If we want to declare a two-dimensional array of double
elements called costs
(for example), we could write any of these:
double[][] costs;
double[] costs[];
double costs[][];
Once again, the first form is more commonly seen (and preferred) in Java code, while the other two are more typical of C.
It’s important to note two things:
The length of an array (or the length of any of a multidimensional array’s dimensions) is not specified in the declaration. Including a number in the brackets of an array declaration will cause compilation to fail. (This differs from C, where the declaration may—and often does—include the size of the array.)
As is the case for all Java object-type fields and variables, declaration of an array does not, by itself, allocate any space for that array. For that, we need to look at “Creation”.