Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior in java

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.

like image 252
abhishek sagar Avatar asked Jul 28 '26 06:07

abhishek sagar


2 Answers

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.

like image 123
Jon Skeet Avatar answered Jul 29 '26 20:07

Jon Skeet


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()[] { ... }
like image 27
Óscar López Avatar answered Jul 29 '26 19:07

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!