5

Possible Duplicate:
java - Array brackets after variable name

When writing a Java function that accepts an array as a parameter, should the function definition have the brackets ("[]") on the type or the variable name?

As in:

private int myFunction(int array[])
{
    //do stuff here
}

or...

private int myFunction(int[] array)
{
    //do stuff here
}

They both "work", but is there a technical difference between the two?

Community
  • 1
  • 1
Aaron
  • 55,518
  • 11
  • 116
  • 132

4 Answers4

15

There is no difference. But int[] array is considered idiomatic Java.

The logic is that [] is part of the type (an array is a distinct type from a scalar), and so int and [] should live together. It's also consistent with the notation for e.g. return types:

int[] foo() {
    ...
    int[] x = new int[5];
    return x;
}
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

When there is single variable it doesn't make much difference, however when its used to define multiple variables

int[] array1, array2;

Will define two arrays.

int array1[], i;

Will define an array and a variable.

Prashant Bhate
  • 10,907
  • 7
  • 47
  • 82
  • 2
    I'd argue that `int array1[], i;` is ugly, as it's declaring variables with two different types. – cHao Dec 24 '11 at 15:29
1

There is no technical difference between the two. I've never seen a style guide that prescribed or preferred the style in your first example. I've also never seen open source Java code that used the style in your first example. It's always int[] array.

Confusion
  • 16,256
  • 8
  • 46
  • 71
0

int[] array makes more sense to me because int[] is the type and array is the name. It makes more sense to keep these separate and standardized.

Liam Cain
  • 13,283
  • 5
  • 39
  • 29