Arrays concept in JAVA

Consider the two ways of declaring an array type variable in Java:

1) Syntax : dataType[] arrayRefVar;

Example:

double[] myList;

2) Syntax: dataType arrayRefVar[];

Example:

double myList[];

Why is the first syntax preferred over the second?

Jon Skeet
people
quotationmark

In the first example, all the type information is in one place - the type of the variable is "array of dataType" so that's what the dataType[] says.

Why would you have two aspects of the type information in different places - one with the element type name and one with the variable?

Note that you can do really confusing things:

int[] x[]; // Equivalent to int[][] x

and

int foo()[] // Equivalent to int[] foo()

Ick!

Also note that the array syntax is closer to the generic syntax if you later want to use a collection type instead of an array. For example:

String[] foo

to

List<String> foo

Basically, the int foo[] syntax was only included in Java to make it look more like C and C++. Personally I think that was a mistake - it can never be removed from the language now, despite the fact that it's strongly discouraged :(

people

See more on this question at Stackoverflow