2

This was asked by a friend. Strangely enough this java code compiles and runs properly.

int getArray() [] { ... }

Am I missing something here. Shouldn't it be

int[] getArray() { ... }

EDIT: getArray() is a function here which returns an integer array.

3 Answers3

9

From section 8.4 of the JLS:

For compatibility with older versions of the Java SE platform, the declaration of a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the formal parameter list. This is supported by the following obsolescent production, but should not be used in new code.

While I occasionally see a variable declaration with the array specifier after the name (ick) I've never seen it used for a method declaration like this. Weird.

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

Both syntaxes for declaring an array are equivalent in Java, as per section §10.2 of the Java Language Specification:

int[] array;
int array[];

The same thing holds true for the return type of a method, as per section §8.4 of the JSL, as quoted in Jon Skeet's answer.

int[] getArray() { ... }
int getArray()[] { ... }
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    That's for a variable - this is a *method* declaration. I was aware of it for variables, but this is the first time I've seen it for a method. – Jon Skeet Apr 08 '12 at 17:59
1

I have seen this in WTF features of java here : https://stackoverflow.com/a/1998146/1247298

Pretty weird when you get to know it for the first time. :)

Community
  • 1
  • 1
Neal
  • 3,119
  • 4
  • 27
  • 32