private String[][] var[]
This code compiles. But shouldn\'t they make the array on type or variable?
This is an example that shows you when the []
position makes a difference.
String[] arr, arr2[];
The arr
is an array of String
whereas the arr2
is an array of arrays of String
.
It can as you see be beneficial if you want to declare different arrays on the same line.
And in your example it could have been another var2
declared on the same line:
private String[][] var[], var2;
The Java Language Specification says
"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"
in JLS 10.2 . In my opinion square brackets ([]
) in "types" make more sense of an array than that is in declared variables. But in order to confirm to the tradition of C/C++ it was done as the text says in JLS. Another thing is , mixing the square bracket with both types and variables would be confusing to the readers/programmers.
According to the JLS 10.2 in the section about Array
's:
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.For example:
byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
byte rowvector[], colvector[], matrix[][];
(Emphasis mine)
Note especially the last example where it says byte[] matrix[]
is equivalent to byte matrix[][]
.
So no, it is not a bug, simply a design choice.
Oscar's answer is pretty good. If one were to read String[][] var[]
in English, one would say "var is an array of two-dimensional String arrays" thus "var is a three-dimensional String array"
The code is the same as this:
private String[][][] var;
All these forms are equivalent:
private String[][][] var;
private String[][] var[];
private String[] var[][];
private String var[][][];
And they all mean the same: a three-dimensional array of strings. The String var[][][]
syntax may seem a bit weird, but it's like that for making C/C++ programmers feel right at home in Java (that's how you normally declare an array type in C/C++).
In Java, the String[][][] var
syntax is preferred, as it makes clear that the type of var
is String[][][]
, in the other syntax and its different variations the type information is split before and after the variable - although it's perfectly legal from the compiler's view point, it's harder to read.
Even weirder, all these method declarations are legal and equivalent:
String[][][] m() {return null;}
String[][] m() [] {return null;}
String[] m() [][] {return null;}
String m() [][][] {return null;}