8

I was updating a legacy code base in Java and I found a line like this:

Object arg[] = { new Integer(20), new Integer(22) };

That line catched my attention because I am used to this kind of code:

Object[] arg = { new Integer(20), new Integer(22) };

The content of the array isn't important here. I'm curious about the brackets next to the variable name versus the brackets next to the class name. I tried in Eclipse (with Java 5) and both lines are valid for the compiler.

Is there any difference between those declarations?

animuson
  • 53,861
  • 28
  • 137
  • 147
JuanZe
  • 8,007
  • 44
  • 58

5 Answers5

16

Both are legal and both work. But placing [] before the array's name is recommended.

From Javadocs:

You can also place the square brackets after the array's name:

float anArrayOfFloats[]; // this form is discouraged

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 3
    Putting the [] with the type is much clearer; try reading the "[]" as "array" - int[] reads as "int array", while int variableName[] sort of tacks the "array" part on as an afterthought. – froadie Feb 09 '10 at 14:47
14

No, they both work. But watch out:

float anArrayOfFloats[], aSecondVariable;

will declare one array of floats and one float, while:

float[] anArrayOfFloats, aSecondVariable;

will declare two arrays of floats.

froadie
  • 79,995
  • 75
  • 166
  • 235
4

There is no difference. Both are legal.

You can read in Java Language Specification http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html

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[];
Pawel Szulc
  • 1,041
  • 2
  • 12
  • 19
1

Another good reason to write Integer[] ints instead of Integer ints[] is because of inheritance relations: Integer[] is subtype of Number[] is subtype of Object[].

In other words, you can put Integers in an Object array, so you can think of the [] as part of the object's type definition -- which is why it makes sense to have it close to the type instead of the object name.

mxk
  • 43,056
  • 28
  • 105
  • 132
0

Short answer: No.

Jay
  • 26,876
  • 10
  • 61
  • 112