And as far as I can see they all run successfully and in fact I can't tell a difference. Is there a rule about when/where the brackets need to be placed in general? If not, what's the difference?
Ernest Friedman-Hill
,
author and iconoclast
staff
In the "C++" language -- whose syntax Java borrows from, heavily -- the brackets always follow the variable name.
int counts[];
The problem with this notation is that it doesn't read well. "int counts array -- oh, an array of int named counts."
Java introduced a variation:
int[] counts;
which reads better -- "int array counts". The two words that describe the type are together, so it's clearer.
Java also allows, for backwards compatibility only, the C++ syntax, with the braces after the variable name. But braces-first is intended as a superior replacement.
As for the space between the type name and the braces: it's optional, as is most whitespace in Java. I personally often omit it -- int[] as oppsed to int [] -- but you should use whatever style suite you or your workplace.
There's actually another reason why the Java version is better: if you declare more than one variable on a line, it does the right thing. In Java, you can say
int[] counts, sizes;
and that means that both "counts" and "sizes" are int arrays. In the C++ syntax, you can say
int counts[], sizes;
and while "counts" is an int array, sizes is not! This is really scary ugly, and you should never do it.