Tiny Tiny - 1 year ago 43
Java Question

Array declaration and initialization in Java. Arrays behave differently, when the position of their subscript indices is changed in their declaration

The following is the obvious and usual array declaration and initialization in Java.

int r[], s[]; //<-------
r=new int[10];
s=new int[10];

A very similar case behaves differently, when the position of
is changed in the declaration statement like as shown below.

int []p, q[]; //<-------
p=new int[10];
q=new int[10][10];

Please look at the declaration. The position of
has been changed from
. In this case, the array
behaves like an array of arrays of type
(which is completely different from the previous case).

The question: Why is
, in this declaration
int []p, q[];
treated as a two dimensional array?

Additional information:

The following syntax looks wonky.

int []a[];

This however, complies fine and just behaves like
int a[][];
int [][]a;

Hence, the following cases are all valid.

int [][]e[][][];
int [][][][][]f[][][][];

Answer Source

Look at JLS on Arrays:

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.


Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rules for variable declaration, however, permit brackets to appear on both the type and in declarators, so that the local variable declaration:

float[][] f[][], g[][][], h[];  // Yechh!

is equivalent to the series of declarations:

float[][][][] f;
float[][][][][] g;
float[][][] h;

So for example:

int []p, q[];

is just

int[] p, q[]

which is in fact

int p[]; int q[][]

The rest are all similar.