35

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 r[] to []p. In this case, the array q behaves like an array of arrays of type int (which is completely different from the previous case).

The question: Why is q, 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[][]; or int [][]a;.

Hence, the following cases are all valid.

int [][]e[][][];
int [][][][][]f[][][][];
3
  • 3
    Try this one public int numbers()[] { return new int[5]; } :D Commented May 25, 2013 at 18:34
  • 1
    Ha, it seems my shot in the dark hits the target:) Commented May 25, 2013 at 18:43
  • Personally, I prefer to declare one array variable per line, and initialize the variable in the same line, in order to avoid this kind of confusion. Commented Jul 3, 2013 at 18:35

2 Answers 2

43

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.

and

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It is strange that q becomes a two dimension array.
@AmirPashazadeh - It's not strange at all if you pretend that the variables are surrounded by parenthesis, ala Perl's syntax my $x, $y; being same as my($x, $y);. If you do this theoretical grouping, you get int[] p, q[] as int[] (p, q[]) => commutatively becoming int[] (p), int[] (q[]) => int []p, int []q[] => int p[], int q[][]
10

The sane way of declaring a variable is

type name

So if type is int[], we should write

int[] array

Never write

int array[]

it is gibberish (though it's legal)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.