Arrays in Java: Declaration

How are simple and multidimensional Java arrays declared?

Overview

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.

Syntax

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: