Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array to a Java function [duplicate]

Tags:

java

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?

like image 510
Aaron Avatar asked Dec 24 '11 15:12

Aaron


3 Answers

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;
}
like image 199
Oliver Charlesworth Avatar answered Oct 15 '22 03:10

Oliver Charlesworth


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.

like image 2
Prashant Bhate Avatar answered Oct 15 '22 03:10

Prashant Bhate


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.

like image 1
Confusion Avatar answered Oct 15 '22 01:10

Confusion