-4

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • whichever is more readable for you and your fellow coders. No behavior/performance difference except readability. – Juned Ahsan Jan 04 '15 at 08:12
  • @JunedAhsan: Well, whichever is most readable for you *and everyone who reads your code*. – Jon Skeet Jan 04 '15 at 08:14
  • format content as per posting guidelines. – askb Jan 04 '15 at 08:16
  • @JonSkeet True, there is no fun without bothering fellow coders ;-) – Juned Ahsan Jan 04 '15 at 08:16
  • The best way of writing the sequence of the array definition components, is to write them the way you spell them: int[] foo is spelled "integer array foo", while int foo[] is spelled "integer foo array", which is not as natural as the first concept. – Costis Aivalis Jan 04 '15 at 11:24

3 Answers3

2

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 :(

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

They are 100% functionally identical but the first form isn't allowed in C or C++ and it's easier to tell that it is an array (in my opinion)

int[] a; // <-- not valid in C (or C++)
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • What do you mean by "only legal in Java"? It's legal in other languages too, and both are legal in Java... – Jon Skeet Jan 04 '15 at 08:13
  • @JonSkeet Edited. Read better? I was trying to say it wasn't legal C or C++. – Elliott Frisch Jan 04 '15 at 08:15
  • I suggest you say exactly that then - given just how many languages there are, including obscure ones, I strongly suspect that Java wasn't the first language ever to use `Foo[]` for an array of `Foo` elements. – Jon Skeet Jan 04 '15 at 08:16
0

There is no difference its just preference of writing came from C and C++ languages.

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.

atish shimpi
  • 4,873
  • 2
  • 32
  • 50