3

Possible Duplicate:
Difference between int[] array and int array[]

I was sure that this question is already asked and just wrote the title to find it, but to my surprise it wasn't. I was working on one issue and this question raised. I tried this:

int[] x = new int[1];
int y[] = new int[1];
x=y;
y=x;

and compiler didn't give me an error. So is there any difference between these two declarations?

Community
  • 1
  • 1
shift66
  • 11,760
  • 13
  • 50
  • 83

3 Answers3

12

There is no difference in semantics. Both syntaxes mean the same. Some extract from the JLS §10.2:

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[][];

However, as Voo states in the below comments, there can be some tricky confusion about these declarations when declaring several arrays in a single statement.

Community
  • 1
  • 1
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
  • Thanks, I thought so too but had to make sure. – shift66 Jan 20 '12 at 14:08
  • 2
    There is a difference though if you define more than one variable per line (which the cited part already hints at). i.e. `int a[], b;` is not the same as `int []a, b;` which may be unexpected. Imho it's best not to use the second variant because it can lead to confusion.That one's actually a legacy from C and iirc Bloch or so later said he regrets including it in the language - could be wrong though. – Voo Jan 20 '12 at 14:11
  • @Voo: Nice remark, I hadn't thought of that yet. Although I usually don't think that declaring several variables in one line is a good idea anyway, especially if their type is not the same as in this example... – Lukas Eder Jan 20 '12 at 14:18
  • @Lukas Yes I agree, although for local variables declaring several on one line is fine I think - that is if they're the same type. But mixing arrays/non arrays? Plain evil imo (although the example from the JLS is even worse - mixing both notations). So if you don't do that it's just a matter of taste - maybe with DRY favoring the second version. Also I just noticed: It obviously should be "best not to use the FIRST variant" in my above comment, not the other way round. – Voo Jan 20 '12 at 14:27
7

There is no difference.

It's just syntactic sugar to make transition from C easier. In Java int[] x is the preferred (and recommended) notation.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

None, it's just a matter of taste. Some people prefer to put it alongside the aggregate type (because feel that it is part of the type), others prefer to put it alongside the variable name (because it's closer to the access syntax).

fortran
  • 74,053
  • 25
  • 135
  • 175