Difference between int[] array and int array[]

Viewed 97713

I have recently been thinking about the difference between the two ways of defining an array:

  1. int[] array
  2. int array[]

Is there a difference?

26 Answers

They are semantically identical. The int array[] syntax was only added to help C programmers get used to java.

int[] array is much preferable, and less confusing.

There is one slight difference, if you happen to declare more than one variable in the same declaration:

int[] a, b;  // Both a and b are arrays of type int
int c[], d;  // WARNING: c is an array, but d is just a regular int

Note that this is bad coding style, although the compiler will almost certainly catch your error the moment you try to use d.

There is no difference.

I prefer the type[] name format at is is clear that the variable is an array (less looking around to find out what it is).

EDIT:

Oh wait there is a difference (I forgot because I never declare more than one variable at a time):

int[] foo, bar; // both are arrays
int foo[], bar; // foo is an array, bar is an int.

No difference.

Quoting from Sun:

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example: byte[] rowvector, colvector, matrix[];

This declaration is equivalent to: byte rowvector[], colvector[], matrix[][];

There isn't any difference between the two; both declare an array of ints. However, the former is preferred since it keeps the type information all in one place. The latter is only really supported for the benefit of C/C++ programmers moving to Java.

There is no real difference; however,

double[] items = new double[10];

is preferred as it clearly indicates that the type is an array.

There is no difference, but Sun recommends putting it next to the type as explained here

In Java, these are simply different syntactic methods of saying the same thing.

They're the same. One is more readable (to some) than the other.

They are completely equivalent. int [] array is the preferred style. int array[] is just provided as an equivalent, C-compatible style.

Yes, there's a difference.

int[] a = new int[100]; // 'a' is not an array itself , the array is stored as an address elsewhere in memory and 'a' holds only that address

int b[] = new int[100]; // while creating array like cleary shows 'b' is an array and it is integer type.

Related