1

I've seen that arrays work when you declare them like this:

int[] myarray = {2,4,6,8,10}; //Notice the brackets are with the type

And when you declare them like this:

int myarray[] = {2,4,6,8,10}; //Here the brackets are with the array name

So which one is the correct way of declaring an array and what are the differences (if any) between the 1st and the 2nd.

Thanks.

HelloUni
  • 448
  • 2
  • 5
  • 10

5 Answers5

5

There is no functional difference at all. It is however considered good practice to put the brackets with the type:

int[] myarray = {2,4,6,8,10};
Keppil
  • 45,603
  • 8
  • 97
  • 119
2

There is no difference but prefer the first declaration.

You can also place the brackets after the array's name:

// this form is discouraged
float anArrayOfFloats[];

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
2

You can declare an int, a one-, and a two-dimensional array, all within a single declaration:

int i, oneD[], twoD[][];

Apart from this use case, you should prefer the early placement of brackets, although both are correct as far as Java specification is concerned.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • While it is correct in the sense that it compiles, this type of declaration violates the [official java coding conventions, section 6.1](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html#2992). – Alderath Dec 27 '13 at 14:02
  • @Alderath Although they are (mostly) right about this one, that particular publication contains a lot of recommendations which nobody in their right mind follows. Such as declaring all your local variables at the top of the method, K&R C-style. – Marko Topolnik Dec 27 '13 at 19:50
1

There is no difference. It's just a Syntactic sugar in array declaration.

Less confusing is the first type, probably.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

They are identical in effect.

The alternate declaration of int myArray[] is a throwback to C, but the type is int[], so the first version int[] myArray is preferrred.

Bohemian
  • 412,405
  • 93
  • 575
  • 722