I have recently been thinking about the difference between the two ways of defining an array:
int[] array
int array[]
While the int integers[]
solution roots in the C language (and can be thus considered the "normal" approach), many people find int[] integers
more logical as it disallows to create variables of different types (i.e. an int and an array) in one declaration (as opposed to the C-style declaration).
They're the same. One is more readable (to some) than the other.
From section 10.2 of the Java Language Specification:
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, as in this example:
byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
byte rowvector[], colvector[], matrix[][];
Personally almost all the Java code I've ever seen uses the first form, which makes more sense by keeping all the type information about the variable in one place. I wish the second form were disallowed, to be honest... but such is life...
Fortunately I don't think I've ever seen this (valid) code:
String[] rectangular[] = new String[10][10];
There is one slight difference, if you happen to declare more than one variable in the same declaration:
int[] a, b; // Both a and b are arrays of type int
int c[], d; // WARNING: c is an array, but d is just a regular int
Note that this is bad coding style, although the compiler will almost certainly catch your error the moment you try to use d
.
Both are equally valid. The int puzzle[]
form is however discouraged, the int[] puzzle
is preferred according to the coding conventions. See also the official Java arrays tutorial:
Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings;
You can also place the square brackets after the array's name:
float anArrayOfFloats[]; // this form is discouraged
However, convention discourages this form; the brackets identify the array type and should appear with the type designation.
Note the last paragraph.
I recommend reading the official Sun/Oracle tutorials rather than some 3rd party ones. You would otherwise risk end up in learning bad practices.
It is an alternative form, which was borrowed from C
, upon which java is based.
As a curiosity, there are three ways to define a valid main
method in java:
public static void main(String[] args)
public static void main(String args[])
public static void main(String... args)